import 'dart:io';
import 'dart:ui';

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/home/captin/map_driver_controller.dart';
import 'package:sefer_driver/views/notification/available_rides_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:sefer_driver/views/home/Captin/home_captain/drawer_captain.dart';
import 'package:sefer_driver/views/widgets/mycircular.dart';
import 'package:bubble_head/bubble.dart';

import '../../../../constant/colors.dart';
import '../../../../constant/info.dart';
import '../../../../constant/style.dart';
import '../../../../controller/functions/location_controller.dart';
import '../../../../controller/functions/overlay_permisssion.dart';
import '../../../../controller/functions/package_info.dart';
import '../../../../controller/home/captin/home_captain_controller.dart';
import '../../../../print.dart';
import '../../../widgets/circle_container.dart';
import '../driver_map_page.dart';
import 'widget/connect.dart';
import 'widget/left_menu_map_captain.dart';
import '../../../../main.dart';

// ==================================================================
// Redesigned Main Widget (V3)
// ==================================================================
class HomeCaptain extends StatelessWidget {
  HomeCaptain({super.key});

  final LocationController locationController = Get.put(LocationController());
  final HomeCaptainController homeCaptainController =
      Get.put(HomeCaptainController());

  @override
  Widget build(BuildContext context) {
    // Initial calls remain the same.
    Get.put(HomeCaptainController());
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      closeOverlayIfFound();
      checkForUpdate(context);
      getPermissionOverlay();
      showDriverGiftClaim(context);
    });

    // The stack is now even simpler.
    return Scaffold(
      appBar: const _HomeAppBar(),
      drawer: AppDrawer(),
      body: Stack(
        children: [
          // 1. The Map View is the base layer.
          const _MapView(),

          // 2. The new floating "Status Pod" at the bottom.
          const _StatusPodOverlay(),

          // This widget from the original code remains.
          leftMainMenuCaptainIcons(),
        ],
      ),
    );
  }
}

// ==================================================================
// Redesigned Helper Widgets (V3)
// ==================================================================

/// 1. The AppBar now contains the map actions in a PopupMenuButton.
class _HomeAppBar extends StatelessWidget implements PreferredSizeWidget {
  const _HomeAppBar();

  @override
  Widget build(BuildContext context) {
    final homeCaptainController = Get.find<HomeCaptainController>();
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 1,
      shadowColor: Colors.black.withOpacity(0.1),
      title: Row(
        children: [
          Image.asset(
            'assets/images/logo.gif',
            height: 35,
          ),
          const SizedBox(width: 10),
          Text(
            AppInformation.appName.split(' ')[0].toString().tr,
            style: AppStyle.title.copyWith(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: AppColor.blueColor,
            ),
          ),
        ],
      ),
      actions: [
        // Refuse count indicator
        Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Center(
            child: MyCircleContainer(
              child: Text(
                homeCaptainController.countRefuse.toString(),
                style: AppStyle.title.copyWith(fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ),
        // The new PopupMenuButton for all map and ride actions.
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 4),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.1),
                spreadRadius: 1,
                blurRadius: 4,
              ),
            ],
          ),
          child: Row(
            children: [
              _MapControlButton(
                icon: Icons.satellite_alt,
                tooltip: 'Change Map Type'.tr,
                onPressed: homeCaptainController.changeMapType,
              ),
              _MapControlButton(
                icon: Icons.streetview_sharp,
                tooltip: 'Toggle Traffic'.tr,
                onPressed: homeCaptainController.changeMapTraffic,
              ),
              _MapControlButton(
                icon: Icons.my_location, // Changed for clarity
                tooltip: 'Center on Me'.tr,
                onPressed: () {
                  if (homeCaptainController.mapHomeCaptainController != null) {
                    homeCaptainController.mapHomeCaptainController!
                        .animateCamera(CameraUpdate.newLatLngZoom(
                      Get.find<LocationController>().myLocation,
                      17.5,
                    ));
                  }
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  PopupMenuItem<String> _buildPopupMenuItem({
    required String value,
    IconData? icon,
    Widget? iconWidget,
    required String text,
    Color? iconColor,
  }) {
    return PopupMenuItem<String>(
      value: value,
      child: Row(
        children: [
          iconWidget ?? Icon(icon, color: iconColor ?? Colors.grey.shade600),
          const SizedBox(width: 16),
          Text(text),
        ],
      ),
    );
  }

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

/// 2. The Map View is unchanged functionally.
class _MapView extends StatelessWidget {
  const _MapView();

  @override
  Widget build(BuildContext context) {
    final locationController = Get.find<LocationController>();
    return GetBuilder<HomeCaptainController>(builder: (controller) {
      return controller.isLoading
          ? const MyCircularProgressIndicator()
          : GoogleMap(
              padding: const EdgeInsets.only(bottom: 110, top: 300),
              fortyFiveDegreeImageryEnabled: true,
              onMapCreated: controller.onMapCreated,
              minMaxZoomPreference: const MinMaxZoomPreference(6, 18),
              initialCameraPosition: CameraPosition(
                target: locationController.myLocation,
                zoom: 15,
              ),
              onCameraMove: (position) {
                CameraPosition(
                  target: locationController.myLocation,
                  zoom: 17.5,
                  tilt: 50.0,
                  bearing: locationController.heading,
                );
              },
              markers: {
                Marker(
                  markerId: MarkerId('MyLocation'.tr),
                  position: locationController.myLocation,
                  rotation: locationController.heading,
                  flat: true,
                  anchor: const Offset(0.5, 0.5),
                  icon: controller.carIcon,
                )
              },
              mapType: controller.mapType ? MapType.satellite : MapType.terrain,
              myLocationButtonEnabled: false,
              myLocationEnabled: false,
              trafficEnabled: controller.mapTrafficON,
              buildingsEnabled: true,
              mapToolbarEnabled: false,
              compassEnabled: true,
              zoomControlsEnabled: false,
            );
    });
  }
}

/// 3. The floating "Status Pod" at the bottom of the screen.
class _StatusPodOverlay extends StatelessWidget {
  const _StatusPodOverlay();

  void _showDetailsDialog(BuildContext context) {
    Get.dialog(
      const _DriverDetailsDialog(),
      barrierColor: Colors.black.withOpacity(0.3),
    );
  }

  @override
  Widget build(BuildContext context) {
    final homeCaptainController = Get.find<HomeCaptainController>();
    return Positioned(
      bottom: 16,
      left: 16,
      right: 16,
      child: GestureDetector(
        onTap: () => _showDetailsDialog(context),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(24),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.85),
                borderRadius: BorderRadius.circular(24),
                border: Border.all(color: Colors.white.withOpacity(0.5)),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20,
                    spreadRadius: -5,
                  )
                ],
              ),
              child: Row(
                children: [
                  const ConnectWidget(),
                  const Spacer(),
                  _buildQuickStat(
                    icon: Icons.directions_car_rounded,
                    value: homeCaptainController.countRideToday,
                    label: 'Rides'.tr,
                    color: AppColor.blueColor,
                  ),
                  const SizedBox(width: 16),
                  _buildQuickStat(
                    icon: Entypo.wallet,
                    value: homeCaptainController.totalMoneyToday.toString(),
                    label: 'Today'.tr,
                    color: AppColor.greenColor,
                  ),
                  const SizedBox(width: 8),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildQuickStat(
      {required IconData icon,
      required String value,
      required String label,
      required Color color}) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          children: [
            Icon(icon, color: color, size: 20),
            const SizedBox(width: 4),
            Text(value,
                style: AppStyle.title
                    .copyWith(fontSize: 16, fontWeight: FontWeight.bold)),
          ],
        ),
        Text(label,
            style: AppStyle.title
                .copyWith(fontSize: 12, color: Colors.grey.shade700)),
      ],
    );
  }
}

/// 4. The Dialog that shows detailed driver stats.
class _DriverDetailsDialog extends StatelessWidget {
  const _DriverDetailsDialog();

  @override
  Widget build(BuildContext context) {
    final homeCaptainController = Get.find<HomeCaptainController>();
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
      child: AlertDialog(
        backgroundColor: Colors.white.withOpacity(0.95),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        titlePadding: const EdgeInsets.only(top: 20),
        title: Center(
          child: Text(
            'Your Activity'.tr,
            style: AppStyle.title
                .copyWith(fontSize: 20, fontWeight: FontWeight.bold),
          ),
        ),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Divider(height: 20),
              _buildStatRow(
                icon: Entypo.wallet,
                color: AppColor.greenColor,
                label: 'Today'.tr,
                value: homeCaptainController.totalMoneyToday.toString(),
              ),
              const SizedBox(height: 12),
              _buildStatRow(
                icon: Entypo.wallet,
                color: AppColor.yellowColor,
                label: AppInformation.appName,
                value: homeCaptainController.totalMoneyInSEFER.toString(),
              ),
              const Divider(height: 24),
              _buildDurationRow(
                icon: Icons.timer_outlined,
                label: 'Active Duration:'.tr,
                value: homeCaptainController.stringActiveDuration,
                color: AppColor.greenColor,
              ),
              const SizedBox(height: 12),
              _buildDurationRow(
                icon: Icons.access_time,
                label: 'Total Connection Duration:'.tr,
                value: homeCaptainController.totalDurationToday,
                color: AppColor.accentColor,
              ),
              const Divider(height: 24),
              _buildStatRow(
                icon: Icons.star_border_rounded,
                color: AppColor.blueColor,
                label: 'Total Points'.tr,
                value: homeCaptainController.totalPoints.toString(),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('Close'.tr,
                style: AppStyle.title.copyWith(
                    color: AppColor.blueColor, fontWeight: FontWeight.bold)),
          )
        ],
      ),
    );
  }

  Widget _buildStatRow(
      {required IconData icon,
      required Color color,
      required String label,
      required String value}) {
    return Row(
      children: [
        Icon(icon, color: color, size: 22),
        const SizedBox(width: 12),
        Text('$label:', style: AppStyle.title),
        const Spacer(),
        Text(
          value,
          style: AppStyle.title.copyWith(
              color: color, fontWeight: FontWeight.bold, fontSize: 18),
        ),
      ],
    );
  }

  Widget _buildDurationRow(
      {required IconData icon,
      required String label,
      required String value,
      required Color color}) {
    return Row(
      children: [
        Icon(icon, color: color, size: 20),
        const SizedBox(width: 12),
        Text(label, style: AppStyle.title),
        const Spacer(),
        Text(
          value,
          style: AppStyle.title.copyWith(
              fontWeight: FontWeight.bold, color: color, fontSize: 16),
        ),
      ],
    );
  }
}

class _MapControlButton extends StatelessWidget {
  final IconData icon;
  final VoidCallback onPressed;
  final String tooltip;

  const _MapControlButton({
    required this.icon,
    required this.onPressed,
    required this.tooltip,
  });

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      message: tooltip,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: onPressed,
          child: Container(
            padding: const EdgeInsets.all(8),
            child: Icon(
              icon,
              size: 24,
              color: AppColor.blueColor,
            ),
          ),
        ),
      ),
    );
  }
}

/// NOTE: The _FloatingActionButtons and _MapControlButton widgets have been removed
/// as their functionality is now integrated into the _HomeAppBar.
///
/// You will still need to modify your existing `ConnectWidget`
/// to accept an `isCompact` boolean flag as mentioned in the previous design.
/*
class ConnectWidget extends StatelessWidget {
  final bool isCompact;
  const ConnectWidget({super.key, this.isCompact = false});

  @override
  Widget build(BuildContext context) {
    // ... your existing controller logic
    
    if (isCompact) {
      // Return a smaller version for the pod
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: controller.isConnect ? AppColor.greenColor : AppColor.accentColor,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(controller.isConnect ? Icons.wifi_tethering_rounded : Icons.wifi_tethering_off_rounded, color: Colors.white, size: 20),
            const SizedBox(width: 8),
            Text(
              controller.isConnect ? 'Online'.tr : 'Offline'.tr,
              style: AppStyle.title.copyWith(color: Colors.white, fontSize: 14),
            ),
          ],
        ),
      );
    }
    
    // Return the original, larger button
    return ElevatedButton.icon(...)
  }
}
*/
