import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:terepi_seged/services/project_service.dart';
import 'package:terepi_seged/services/stakeout_export_service.dart';
import 'package:terepi_seged/services/stakeout_service.dart';

import '../../../../models/stakeout_point.dart';

/// Kitűzési pontlista — bottom sheet a panelről.
///
/// Szűrés státusz és vonal szerint; soronként távolság a jelenlegi
/// pozíciótól, kitűzötteknél az eltérések; koppintás = az legyen a cél;
/// menü: kihagyás / visszaállítás / törlés. Fejlécből CSV-export
/// (magyar Excel-barát vagy nemzetközi dialektus).
class StakeoutListSheet extends StatefulWidget {
  const StakeoutListSheet({super.key});

  static Future<void> show() {
    return Get.bottomSheet(
      const StakeoutListSheet(),
      isScrollControlled: true,
    );
  }

  @override
  State<StakeoutListSheet> createState() => _StakeoutListSheetState();
}

class _StakeoutListSheetState extends State<StakeoutListSheet> {
  StakeoutStatus? _statusFilter; // null = mind
  String? _lineFilter; // null = mind

  StakeoutService get svc => StakeoutService.to;

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return SafeArea(
      top: false,
      child: Material(
        color: colorScheme.surface,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
        clipBehavior: Clip.antiAlias,
        child: ConstrainedBox(
          constraints: BoxConstraints(
              maxHeight: MediaQuery.sizeOf(context).height * 0.85),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 42,
                height: 4,
                margin: const EdgeInsets.only(top: 12, bottom: 8),
                decoration: BoxDecoration(
                  color: colorScheme.outlineVariant,
                  borderRadius: BorderRadius.circular(999),
                ),
              ),

              // ── Fejléc + export ────────────────────────────────
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    const Icon(Icons.list_alt),
                    const SizedBox(width: 8),
                    Obx(() => Text(
                          'Kitűzési pontok (${svc.points.length})',
                          style: Theme.of(context).textTheme.titleMedium,
                        )),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.ios_share),
                      tooltip: 'Export CSV',
                      onPressed: _exportDialog,
                    ),
                  ],
                ),
              ),

              // ── Szűrők ─────────────────────────────────────────
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12),
                child: Row(
                  children: [
                    Expanded(
                      child: SegmentedButton<StakeoutStatus?>(
                        segments: const [
                          ButtonSegment(value: null, label: Text('Mind')),
                          ButtonSegment(
                              value: StakeoutStatus.pending,
                              label: Text('Vár')),
                          ButtonSegment(
                              value: StakeoutStatus.staked,
                              label: Text('Kész')),
                          ButtonSegment(
                              value: StakeoutStatus.skipped,
                              label: Text('Kihagyva')),
                        ],
                        selected: {_statusFilter},
                        onSelectionChanged: (s) =>
                            setState(() => _statusFilter = s.first),
                        showSelectedIcon: false,
                        style: const ButtonStyle(
                            visualDensity: VisualDensity.compact,
                            tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Obx(() {
                      final lines = svc.lines;
                      if (lines.length <= 1) return const SizedBox.shrink();
                      return DropdownButton<String?>(
                        value: _lineFilter,
                        hint:
                            const Text('Vonal', style: TextStyle(fontSize: 12)),
                        items: [
                          const DropdownMenuItem(
                              value: null, child: Text('Mind')),
                          for (final l in lines)
                            DropdownMenuItem(
                                value: l,
                                child: Text(l.isEmpty ? '(nincs)' : l)),
                        ],
                        onChanged: (v) => setState(() => _lineFilter = v),
                      );
                    }),
                  ],
                ),
              ),
              const Divider(height: 12),

              // ── Lista ──────────────────────────────────────────
              Flexible(
                child: Obx(() {
                  var rows = svc.points.toList();
                  if (_statusFilter != null) {
                    rows =
                        rows.where((p) => p.status == _statusFilter).toList();
                  }
                  if (_lineFilter != null) {
                    rows = rows.where((p) => p.lineId == _lineFilter).toList();
                  }
                  rows.sort((a, b) => a.lineId != b.lineId
                      ? a.lineId.compareTo(b.lineId)
                      : a.station.compareTo(b.station));

                  if (rows.isEmpty) {
                    return const Padding(
                      padding: EdgeInsets.all(32),
                      child: Text('Nincs a szűrésnek megfelelő pont.'),
                    );
                  }

                  return ListView.builder(
                    shrinkWrap: true,
                    itemCount: rows.length,
                    itemBuilder: (context, i) => _row(context, rows[i]),
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _row(BuildContext context, StakeoutPoint p) {
    final isTarget = svc.target.value?.uuid == p.uuid;

    final (color, icon) = switch (p.status) {
      StakeoutStatus.staked => (Colors.green, Icons.check_circle),
      StakeoutStatus.skipped => (Colors.grey, Icons.block),
      StakeoutStatus.pending => (
          Colors.deepOrange,
          Icons.radio_button_unchecked
        ),
    };

    // Távolság a jelenlegi pozíciótól (ha van).
    String distText = '';
    if (svc.hasPosition.value) {
      final dy = p.planEovY - svc.curEovY.value;
      final dx = p.planEovX - svc.curEovX.value;
      final d = math.sqrt(dy * dy + dx * dx);
      distText = d >= 1000
          ? '${(d / 1000).toStringAsFixed(1)} km'
          : '${d.toStringAsFixed(0)} m';
    }

    String cm(double? v) => v == null ? '—' : '${(v * 100).toStringAsFixed(0)}';

    final sub = p.status == StakeoutStatus.staked
        ? 'in ${cm(p.devInline)} · cross ${cm(p.devCrossline)}'
            '${p.devDz != null ? ' · dZ ${cm(p.devDz)}' : ''} cm'
        : [
            if (distText.isNotEmpty) distText,
            if (p.isOffset) 'eltolt (${p.offsetDist?.toStringAsFixed(1)} m)',
          ].join(' · ');

    return ListTile(
      dense: true,
      selected: isTarget,
      leading: Icon(icon, color: color, size: 20),
      title: Text(p.displayId,
          style: TextStyle(
              fontWeight: isTarget ? FontWeight.w700 : FontWeight.w500)),
      subtitle:
          sub.isEmpty ? null : Text(sub, style: const TextStyle(fontSize: 11)),
      onTap: () {
        svc.setTarget(p);
        Get.back();
      },
      trailing: PopupMenuButton<String>(
        onSelected: (a) async {
          switch (a) {
            case 'target':
              svc.setTarget(p);
              Get.back();
            case 'skip':
              await svc.setPointStatus(p, StakeoutStatus.skipped);
            case 'restore':
              await svc.setPointStatus(p, StakeoutStatus.pending);
            case 'delete':
              final ok = await Get.dialog<bool>(AlertDialog(
                title: const Text('Pont törlése'),
                content: Text('${p.displayId} törlése a kitűzési listából?'),
                actions: [
                  TextButton(
                      onPressed: () => Get.back(result: false),
                      child: const Text('Mégse')),
                  FilledButton(
                      onPressed: () => Get.back(result: true),
                      child: const Text('Törlés')),
                ],
              ));
              if (ok == true) await svc.deletePoint(p);
          }
        },
        itemBuilder: (_) => [
          const PopupMenuItem(value: 'target', child: Text('Ez legyen a cél')),
          if (p.status != StakeoutStatus.skipped)
            const PopupMenuItem(value: 'skip', child: Text('Kihagyás')),
          if (p.status != StakeoutStatus.pending)
            const PopupMenuItem(
                value: 'restore', child: Text('Visszaállítás várakozóra')),
          const PopupMenuItem(value: 'delete', child: Text('Törlés')),
        ],
      ),
    );
  }

  // ── Export dialógus ────────────────────────────────────────────

  Future<void> _exportDialog() async {
    final hungarian = true.obs;
    final stakedOnly = false.obs;

    await Get.dialog(AlertDialog(
      title: const Text('Export CSV'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Obx(() => SwitchListTile(
                contentPadding: EdgeInsets.zero,
                dense: true,
                title: const Text('Magyar Excel-formátum'),
                subtitle: const Text('pontosvessző + tizedesvessző',
                    style: TextStyle(fontSize: 11)),
                value: hungarian.value,
                onChanged: (v) => hungarian.value = v,
              )),
          Obx(() => SwitchListTile(
                contentPadding: EdgeInsets.zero,
                dense: true,
                title: const Text('Csak a kitűzött pontok'),
                value: stakedOnly.value,
                onChanged: (v) => stakedOnly.value = v,
              )),
        ],
      ),
      actions: [
        TextButton(onPressed: Get.back, child: const Text('Mégse')),
        FilledButton.icon(
          icon: const Icon(Icons.ios_share, size: 18),
          label: const Text('Export'),
          onPressed: () async {
            Get.back();
            try {
              await StakeoutExportService.exportAndShare(
                points: svc.points.toList(),
                hungarian: hungarian.value,
                stakedOnly: stakedOnly.value,
                projectName: ProjectService.to.activeProject.value?.name ?? '',
              );
            } catch (e) {
              Get.snackbar('Export', e.toString(),
                  snackPosition: SnackPosition.BOTTOM);
            }
          },
        ),
      ],
    ));
  }
}
