import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/controller/home/captin/map_driver_controller.dart';

import '../../../constant/colors.dart';
import '../../../controller/functions/location_controller.dart';
import '../../../main.dart';
import '../../Rate/rate_passenger.dart';
import '../../widgets/my_textField.dart';
import 'mapDriverWidgets/driver_end_ride_bar.dart';
import 'mapDriverWidgets/google_driver_map_page.dart';
import 'mapDriverWidgets/google_map_app.dart';
import 'mapDriverWidgets/passenger_info_window.dart';
import 'mapDriverWidgets/sos_connect.dart';

class PassengerLocationMapPage extends StatelessWidget {
  PassengerLocationMapPage({super.key});
  final LocationController locationController = Get.put(LocationController());
  final MapDriverController mapDriverController =
      Get.put(MapDriverController());

  // Helper function to show exit confirmation dialog
  Future<bool> showExitDialog() async {
    bool? result = await Get.defaultDialog(
      title: "Warning".tr,
      titleStyle: AppStyle.title.copyWith(color: AppColor.redColor),
      middleText:
          "You are in an active ride. Leaving this screen might stop tracking. Are you sure you want to exit?"
              .tr,
      middleTextStyle: AppStyle.title,
      barrierDismissible: false,
      confirm: MyElevatedButton(
        title: 'Stay'.tr,
        kolor: AppColor.greenColor,
        onPressed: () => Get.back(result: false), // Return false (Don't pop)
      ),
      cancel: MyElevatedButton(
        title: 'Exit'.tr,
        kolor: AppColor.redColor,
        onPressed: () => Get.back(result: true), // Return true (Allow pop)
      ),
    );
    return result ?? false;
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (Get.arguments != null && Get.arguments is Map<String, dynamic>) {
        mapDriverController.argumentLoading();
        mapDriverController.startTimerToShowPassengerInfoWindowFromDriver();
      }
    });

    // ✅ Added PopScope to intercept back button
    return PopScope(
      canPop: false, // Prevents immediate popping
      onPopInvokedWithResult: (didPop, result) async {
        if (didPop) {
          return;
        }
        // Show dialog
        final shouldExit = await showExitDialog();
        if (shouldExit) {
          Get.back(); // Manually pop if confirmed
        }
      },
      child: Scaffold(
          body: SafeArea(
        child: Stack(
          children: [
            // 1. Map
            GoogleDriverMap(locationController: locationController),

            // 2. Instructions
            const InstructionsOfRoads(),

            // 3. Passenger Info
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: PassengerInfoWindow(),
            ),

            // 4. Cancel Widget
            CancelWidget(mapDriverController: mapDriverController),

            // 5. End Ride Bar
            driverEndRideBar(),

            // 6. SOS
            SosConnect(),

            // 7. Speed
            speedCircle(),

            // 8. External Map
            Positioned(
              bottom: 100,
              right: 10,
              child: GoogleMapApp(),
            ),

            // 9. Prices Window
            const PricesWindow(),
          ],
        ),
      )),
    );
  }
}

// ... The rest of your widgets (InstructionsOfRoads, CancelWidget, etc.) remain unchanged ...
// ... Keep the code below exactly as you had it in the previous snippet ...

class InstructionsOfRoads extends StatelessWidget {
  const InstructionsOfRoads({super.key});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: 10,
      left: MediaQuery.of(context).size.width * 0.15,
      right: MediaQuery.of(context).size.width * 0.15,
      child: GetBuilder<MapDriverController>(
        builder: (controller) => controller.currentInstruction.isNotEmpty
            ? AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(30),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.directions, color: AppColor.primaryColor),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Text(
                        controller.currentInstruction,
                        style: AppStyle.title.copyWith(fontSize: 16),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 10),
                    InkWell(
                      onTap: () {
                        controller.toggleTts();
                      },
                      child: Icon(
                        controller.isTtsEnabled
                            ? Icons.volume_up
                            : Icons.volume_off,
                        color: controller.isTtsEnabled
                            ? AppColor.greenColor
                            : Colors.grey,
                      ),
                    ),
                  ],
                ),
              )
            : const SizedBox(),
      ),
    );
  }
}

class CancelWidget extends StatelessWidget {
  const CancelWidget({
    super.key,
    required this.mapDriverController,
  });

  final MapDriverController mapDriverController;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 70,
      left: 10,
      child: GetBuilder<MapDriverController>(
        builder: (controller) {
          if (controller.isRideFinished) return const SizedBox.shrink();

          return GestureDetector(
            onTap: () {
              Get.defaultDialog(
                  title: "Are you sure you want to cancel this trip?".tr,
                  titleStyle: AppStyle.title,
                  content: Column(
                    children: [
                      Text("Why do you want to cancel this trip?".tr),
                      Form(
                          key: mapDriverController.formKeyCancel,
                          child: MyTextForm(
                            controller: mapDriverController.cancelTripCotroller,
                            label: "Write the reason for canceling the trip".tr,
                            hint: "Write the reason for canceling the trip".tr,
                            type: TextInputType.name,
                          ))
                    ],
                  ),
                  confirm: MyElevatedButton(
                      title: 'Ok'.tr,
                      kolor: AppColor.redColor,
                      onPressed: () async {
                        await mapDriverController
                            .cancelTripFromDriverAfterApplied();
                        Get.back();
                      }),
                  cancel: MyElevatedButton(
                      title: 'No'.tr,
                      onPressed: () {
                        Get.back();
                      }));
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 5,
                  ),
                ],
              ),
              child: const Padding(
                padding: EdgeInsets.all(8.0),
                child: Icon(
                  Icons.clear,
                  size: 30,
                  color: AppColor.redColor,
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

class PricesWindow extends StatelessWidget {
  const PricesWindow({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapDriverController>(builder: (mapDriverController) {
      return mapDriverController.isPriceWindow
          ? Container(
              color: Colors.black.withOpacity(0.5),
              child: Center(
                child: Container(
                  width: Get.width * 0.8,
                  padding: const EdgeInsets.all(24),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'Total Price is '.tr,
                        style: AppStyle.headTitle2,
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 10),
                      Text(
                        '${mapDriverController.totalPricePassenger} ${'\$'.tr}',
                        style: AppStyle.headTitle2.copyWith(
                            color: AppColor.primaryColor, fontSize: 36),
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                      MyElevatedButton(
                          title: 'ok'.tr,
                          onPressed: () =>
                              Get.to(() => RatePassenger(), arguments: {
                                'rideId': mapDriverController.rideId,
                                'passengerId': mapDriverController.passengerId,
                                'driverId': mapDriverController.driverId
                              }))
                    ],
                  ),
                ),
              ),
            )
          : const SizedBox();
    });
  }
}
