import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';

import '../controllers/tracking_controller.dart';
import '../../../../models/track.dart';

/// Mentett track-ek listája megtekintési és export lehetőséggel.
class TrackListView extends GetView<TrackingController> {
  const TrackListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mentett track-ek'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.loadSavedTracks,
          )
        ],
      ),
      body: Obx(() {
        final tracks = controller.savedTracks;
        if (tracks.isEmpty) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.route, size: 64, color: Colors.grey.shade300),
                const SizedBox(height: 12),
                Text('Még nincs mentett nyomvonal',
                    style: TextStyle(color: Colors.grey.shade500)),
              ],
            ),
          );
        }

        return ListView.separated(
          padding: const EdgeInsets.symmetric(vertical: 8),
          itemCount: tracks.length,
          separatorBuilder: (_, __) => const Divider(height: 1),
          itemBuilder: (context, i) => _TrackTile(track: tracks[i]),
        );
      }),
    );
  }
}

class _TrackTile extends GetView<TrackingController> {
  final Track track;
  const _TrackTile({required this.track});

  @override
  Widget build(BuildContext context) {
    final statusColor = switch (track.status) {
      TrackStatus.recording => Colors.red,
      TrackStatus.paused => Colors.orange,
      TrackStatus.finished => Colors.green,
    };

    return Dismissible(
      key: ValueKey(track.id),
      direction: DismissDirection.endToStart,
      confirmDismiss: (_) => _confirm(context),
      onDismissed: (_) => controller.deleteTrack(track.id!),
      background: Container(
        color: Colors.red,
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: statusColor.withOpacity(0.15),
          child: Icon(Icons.route, color: statusColor),
        ),
        title: Text(track.name,
            style: const TextStyle(fontWeight: FontWeight.w600)),
        subtitle: Text(
          '${track.distanceFormatted}  ·  ${track.durationFormatted}'
          '  ·  ${track.pointCount} pont\n${track.source}',
        ),
        isThreeLine: true,
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.map_outlined),
              tooltip: 'Megtekintés',
              onPressed: () => Get.to(() => _TrackPreviewView(track: track)),
            ),
            IconButton(
              icon: const Icon(Icons.share),
              tooltip: 'GPX export',
              onPressed: () => controller.exportTrack(track),
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> _confirm(BuildContext context) async {
    return await showDialog<bool>(
          context: context,
          builder: (_) => AlertDialog(
            title: const Text('Track törlése'),
            content: Text('"${track.name}" törlése visszavonohatalan.'),
            actions: [
              TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: const Text('Mégse')),
              FilledButton.tonal(
                  style: FilledButton.styleFrom(
                      backgroundColor: Colors.red.shade50),
                  onPressed: () => Navigator.pop(context, true),
                  child: const Text('Törlés',
                      style: TextStyle(color: Colors.red))),
            ],
          ),
        ) ??
        false;
  }
}

// ─── Track előnézeti térkép ──────────────────────────────────────────────────

class _TrackPreviewView extends GetView<TrackingController> {
  final Track track;
  const _TrackPreviewView({required this.track});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(track.name),
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () => controller.exportTrack(track),
          )
        ],
      ),
      body: FutureBuilder<List<LatLng>>(
        future: controller.loadTrackPoints(track.id!),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('Hiba: ${snapshot.error}'));
          }
          final points = snapshot.data ?? [];
          if (points.isEmpty) {
            return const Center(child: Text('Nincs megjeleníthető pont.'));
          }

          // Bounding box számítás automatikus zoom-hoz
          final lats = points.map((p) => p.latitude).toList();
          final lons = points.map((p) => p.longitude).toList();
          final center = LatLng(
            (lats.reduce((a, b) => a + b)) / lats.length,
            (lons.reduce((a, b) => a + b)) / lons.length,
          );

          return Column(
            children: [
              Expanded(
                child: FlutterMap(
                  options: MapOptions(
                    initialCenter: center,
                    initialZoom: 14,
                    initialCameraFit: CameraFit.coordinates(
                      coordinates: points,
                      padding: const EdgeInsets.all(40),
                    ),
                  ),
                  children: [
                    TileLayer(
                      urlTemplate:
                          'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                      userAgentPackageName: 'hu.app_dev.terepi_seged',
                    ),
                    PolylineLayer(
                      polylines: [
                        Polyline(
                          points: points,
                          color: Colors.blue.shade700,
                          strokeWidth: 4.0,
                          borderColor: Colors.blue.shade200,
                          borderStrokeWidth: 1.5,
                        ),
                      ],
                    ),
                    MarkerLayer(
                      markers: [
                        Marker(
                          point: points.first,
                          child: const Icon(Icons.flag,
                              color: Colors.green, size: 28),
                        ),
                        Marker(
                          point: points.last,
                          child: const Icon(Icons.flag,
                              color: Colors.red, size: 28),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              // Statisztika sáv alul
              Container(
                color: Theme.of(context).colorScheme.surface,
                padding: EdgeInsets.fromLTRB(
                    24, 12, 24, 12 + MediaQuery.of(context).padding.bottom),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _InfoChip(
                        icon: Icons.straighten, text: track.distanceFormatted),
                    _InfoChip(
                        icon: Icons.timer_outlined,
                        text: track.durationFormatted),
                    _InfoChip(
                        icon: Icons.location_on_outlined,
                        text: '${track.pointCount} pont'),
                    _InfoChip(icon: Icons.sensors, text: track.source),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _InfoChip extends StatelessWidget {
  final IconData icon;
  final String text;
  const _InfoChip({required this.icon, required this.text});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 15, color: Theme.of(context).colorScheme.primary),
        const SizedBox(width: 4),
        Text(text, style: const TextStyle(fontSize: 13)),
      ],
    );
  }
}
