import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:get/state_manager.dart';
import 'package:terepi_seged/pages/map_survey/presentations/controllers/map_survey_controller.dart';
import 'package:terepi_seged/pages/shell/presentations/controllers/shell_controller.dart';
import 'package:terepi_seged/pages/tracking/presentation/controllers/tracking_controller.dart';
import 'package:terepi_seged/services/gnss/gnss_service.dart';
import 'package:terepi_seged/services/ntrip_service.dart';
import 'package:terepi_seged/widgets/appbar/gnss_status_strip.dart';
import 'package:terepi_seged/widgets/gnss_status_chip.dart';
import 'package:terepi_seged/widgets/map_mode_menu_anchor.dart';
import 'package:terepi_seged/widgets/ntrip_status_sheet.dart';
import 'package:terepi_seged/widgets/tracking/track_recording_action.dart';

import '../tracking/tracking_sheet.dart';
import 'gnss_receiver_icon.dart';
import 'gnss_receiver_outline_icon.dart';

class ShellMapAppBar extends StatelessWidget implements PreferredSizeWidget {
  final MapSurveyController controller;

  const ShellMapAppBar({
    super.key,
    required this.controller,
  });

  @override
  Size get preferredSize => const Size.fromHeight(72);

  @override
  Widget build(BuildContext context) {
    return AppBar(
        toolbarHeight: 50,
        automaticallyImplyLeading: false,
        //leadingWidth: 44,
        actionsPadding: EdgeInsets.zero,
        titleSpacing: 0,
        leading: Builder(builder: (context) {
          return IconButton(
            //padding: EdgeInsets.zero,
            visualDensity: VisualDensity.compact,
            //constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
            icon: const Icon(Icons.menu),
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
          );
        }),
        title: Row(children: [
          MapModeMenuAnchor(controller: controller),
          const SizedBox(width: 2),
          // Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     mainAxisSize: MainAxisSize.max,
          //     mainAxisAlignment: MainAxisAlignment.start,
          //     children: [
          //       Row(children: [
          //         const Text('H:', style: TextStyle(fontSize: 12)),
          //         SizedBox(width: 2),
          //         Text(controller.horizontalAccuracyText,
          //             style: TextStyle(
          //                 fontSize: 12,
          //                 color: _errorColor(max(
          //                     controller.gpsLatitudeError.value,
          //                     controller.gpsLongitudeError.value)),
          //                 fontWeight: FontWeight.w600,
          //                 fontFeatures: const [FontFeature.tabularFigures()]))
          //       ]),
          //       Row(children: [
          //         const Text('V:', style: TextStyle(fontSize: 12)),
          //         SizedBox(width: 2),
          //         Text(controller.verticalAccuracyText,
          //             style: TextStyle(
          //                 fontSize: 12,
          //                 color:
          //                     _errorColor(controller.gpsAltitudeError.value),
          //                 fontWeight: FontWeight.w600,
          //                 fontFeatures: const [FontFeature.tabularFigures()]))
          //       ])
          //     ]),
          // SizedBox(width: 8),
          // Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     mainAxisSize: MainAxisSize.max,
          //     mainAxisAlignment: MainAxisAlignment.start,
          //     children: [
          //       GnssTextStatusChip(),
          //       Row(children: [
          //         const Icon(Icons.satellite_alt, size: 12),
          //         SizedBox(width: 2),
          //         Text(
          //             '${GnssService.to.totalVisibleSatellites}/${GnssService.to.totalUsedSatellites}',
          //             style: TextStyle(
          //                 fontSize: 12,
          //                 fontWeight: FontWeight.w600,
          //                 fontFeatures: const [FontFeature.tabularFigures()]))
          //       ])
          //     ]),
          // const GnssIconStatusChip(),
          const SizedBox(width: 2),
          NtripIconStatusChip(
              isConnected: NtripService.to.isConnected,
              onToggle: () {
                NtripStatusSheet.show();
              },
              onSettings: () {
                HapticFeedback.mediumImpact();
                controller.openNtripsettings();
              }),
        ]),
        actions: [
          const GnssIconStatusChip(),
          // Obx(() {
          //   final isRec = TrackingController.to.isRecording.value;
          //   return Badge(
          //     isLabelVisible: isRec,
          //     label: null, // csak piros pont, szám nélkül
          //     backgroundColor: Colors.red,
          //     child: IconButton(
          //       icon: const Icon(Icons.route_outlined),
          //       tooltip: 'Nyomvonal',
          //       onPressed: () => _openTrackingSheet(context),
          //     ),
          //   );
          // }),
          // Obx(() {
          //   final connected = controller.gpsIsConnected;

          //   return IconButton(
          //     tooltip: connected
          //         ? 'GNSS vevő csatlakozva'
          //         : 'GNSS vevő nincs csatlakoztatva',
          //     visualDensity: VisualDensity.compact,
          //     padding: EdgeInsets.zero,
          //     constraints: const BoxConstraints(
          //       minWidth: 40,
          //       minHeight: 44,
          //     ),
          //     icon: GnssReceiverIcon(
          //       size: 24,
          //       color: connected
          //           ? Colors.green.shade700
          //           : Theme.of(context).colorScheme.onSurfaceVariant,
          //     ),
          //     onPressed: () {},
          //   );
          // }),
          TrackRecordingAction(
            controller: TrackingController.to,
            onTap: () => _openTrackingSheet(context),
          ),
          PopupMenuButton<int>(
              tooltip: 'További funkciók',
              icon: const Icon(Icons.more_vert),
              onSelected: (value) {
                if (value == 1) {
                  controller.openLayerPanel();
                }
                if (value == 0) {
                  controller.openNoteItemList();
                }
                if (value == 2) {
                  controller.toggleGeometryLabels();
                }
                if (value == 3) {
                  controller.exportProject();
                }
              },
              itemBuilder: (context) => [
                    PopupMenuItem(
                      value: 0,
                      child: ListTile(
                          leading: Icon(Icons.line_axis),
                          title: Text('Geometriák'),
                          dense: true),
                    ),
                    PopupMenuItem(
                      value: 2,
                      child: ListTile(
                        leading: Icon(
                            controller.showGeometryLabels.value
                                ? Icons.label
                                : Icons.label_off_outlined,
                            color: controller.showGeometryLabels.value
                                ? Theme.of(context).colorScheme.primary
                                : null),
                        title: Text(controller.showGeometryLabels.value
                            ? "Feliartok elrejtése"
                            : 'Feliratok megjelenítése'),
                      ),
                    ),
                    PopupMenuItem(
                      value: 1,
                      child: Text('Rétegek'),
                    ),
                    PopupMenuDivider(),
                    PopupMenuItem(
                        value: 3,
                        child: ListTile(
                          leading: const Icon(Icons.archive_outlined),
                          title: const Text('Projekt exportálása'),
                          dense: true,
                        ))
                  ])
        ],
        bottom: PreferredSize(
            preferredSize: const Size.fromHeight(28),
            child: GnssStatusStrip(controller: controller)));
  }

  Color _errorColor(double e) {
    if (e < 0.05) return Colors.greenAccent;
    if (e < 0.2) return Colors.green;
    if (e < 1.0) return Colors.orange;
    return Colors.red;
  }

  void _openTrackingSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => const TrackingSheet(),
    );
  }
}
