import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:terepi_seged/models/track.dart';
import 'package:terepi_seged/pages/tracking/presentation/controllers/tracking_controller.dart';

class TrackListItem extends StatelessWidget {
  final Track track;

  const TrackListItem({
    super.key,
    required this.track,
  });

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final ctrl = TrackingController.to;
      final isOverlay = ctrl.overlayTrackIds.contains(track.id);

      return ListTile(
        leading: CircleAvatar(
          backgroundColor: isOverlay
              ? Colors.blue.withOpacity(0.2)
              : Theme.of(context).colorScheme.surfaceVariant,
          child: Icon(Icons.route,
              color: isOverlay ? Colors.blue : Colors.grey, size: 20),
        ),
        title: Text(track.name, style: const TextStyle(fontSize: 13)),
        subtitle: Text(
          '${_fmtDist(track.distanceMeters)}  ·  '
          '${track.durationFormatted}  ·  '
          '${track.pointCount} pt',
          style: const TextStyle(fontSize: 11),
        ),
        trailing: Row(mainAxisSize: MainAxisSize.min, children: [
          // Overlay kapcsoló
          IconButton(
            icon: Icon(
              isOverlay ? Icons.layers : Icons.layers_outlined,
              color: isOverlay ? Colors.blue : null,
              size: 20,
            ),
            tooltip: isOverlay ? 'Elrejt' : 'Mutat a térképen',
            onPressed: () {
              ctrl.toggleTrackOverlay(track.id!);
              // Ha bekapcsolta → zárjuk be a sheet-et
              // hogy lássa a térképet
              if (!isOverlay) Navigator.pop(context);
            },
          ),

          // Export
          IconButton(
            icon: const Icon(Icons.share, size: 20),
            onPressed: () => ctrl.exportTrack(track),
          ),
        ]),
      );
    });
  }

  String _fmtDist(double m) => m < 1000
      ? '${m.toStringAsFixed(0)} m'
      : '${(m / 1000).toStringAsFixed(2)} km';
}
