import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/firebase/local_notification.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/captin/otp_page.dart';
import 'package:sefer_driver/views/home/Captin/driver_map_page.dart';
import 'package:sefer_driver/views/home/Captin/orderCaptin/vip_order_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/controller/home/captin/home_captain_controller.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';

import '../../../../../constant/colors.dart';
import '../../../../../constant/links.dart';
import '../../../../../controller/firebase/firbase_messge.dart';
import '../../../../../controller/firebase/notification_service.dart';
import '../../../../../controller/functions/crud.dart';
import '../../../../../controller/home/captin/order_request_controller.dart';
import '../../../../../controller/home/navigation/navigation_view.dart';
import '../../../../../print.dart';
import '../../../../Rate/ride_calculate_driver.dart';

GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
  final firebaseMessagesController =
      Get.isRegistered<FirebaseMessagesController>()
          ? Get.find<FirebaseMessagesController>()
          : Get.put(FirebaseMessagesController());
  return GetBuilder<HomeCaptainController>(
    builder: (controller) => Positioned(
      bottom: Get.height * .2,
      left: 6,
      child: Column(
        children: [
          AnimatedContainer(
            duration: const Duration(microseconds: 200),
            width: controller.widthMapTypeAndTraffic,
            decoration: BoxDecoration(
                color: AppColor.secondaryColor,
                border: Border.all(color: AppColor.blueColor),
                borderRadius: BorderRadius.circular(15)),
            child: Builder(builder: (context) {
              return IconButton(
                onPressed: () async {
                  await checkForPendingOrderFromServer();
                  box.read(BoxName.rideArgumentsFromBackground) != 'failure'
                      ? Get.to(() => PassengerLocationMapPage(),
                          arguments:
                              box.read(BoxName.rideArgumentsFromBackground))
                      : MyDialog().getDialog(
                          'Ride info'.tr,
                          'you dont have accepted ride'.tr,
                          () {
                            Get.back();
                          },
                        );
                  //     'box.read(BoxName.rideArgumentsFromBackground): ${box.read(BoxName.rideArgumentsFromBackground)}');
                },
                icon: Icon(
                  Icons.directions_car_rounded,
                  size: 29,
                  color:
                      box.read(BoxName.rideArgumentsFromBackground) == 'failure'
                          ? AppColor.redColor
                          : AppColor.greenColor,
                ),
              );
            }),
          ),

          const SizedBox(
            height: 5,
          ),
          AnimatedContainer(
            duration: const Duration(microseconds: 200),
            width: controller.widthMapTypeAndTraffic,
            decoration: BoxDecoration(
                color: AppColor.secondaryColor,
                border: Border.all(color: AppColor.blueColor),
                borderRadius: BorderRadius.circular(15)),
            child: IconButton(
              onLongPress: () {
                box.write(BoxName.statusDriverLocation, 'off');
              },
              onPressed: () {
                // NotificationController1()
                //     .showNotification('Sefer Driver'.tr, ''.tr, '', '');
                final now = DateTime.now();
                DateTime? lastRequestTime =
                    box.read(BoxName.lastTimeStaticThrottle);

                if (lastRequestTime == null ||
                    now.difference(lastRequestTime).inMinutes >= 2) {
                  // Update the last request time to now
                  lastRequestTime = now;
                  box.write(BoxName.lastTimeStaticThrottle, lastRequestTime);
                  // Navigate to the RideCalculateDriver page
                  Get.to(() => RideCalculateDriver());
                } else {
                  // Optionally show a message or handle the throttling case
                  final minutesLeft =
                      2 - now.difference(lastRequestTime).inMinutes;
                  // Get.snackbar(
                  //     '${'Please wait'.tr} $minutesLeft ${"minutes before trying again.".tr}',
                  //     '');
                  NotificationController().showNotification(
                      'Intaleq Driver'.tr,
                      '${'Please wait'.tr} $minutesLeft ${"minutes before trying again.".tr}',
                      'ding',
                      '');
                }
              },
              icon: const Icon(
                FontAwesome5.chart_bar,
                size: 29,
                color: AppColor.blueColor,
              ),
            ),
          ),

          const SizedBox(
            height: 5,
          ),
          // Platform.isAndroid
          // ?
          int.parse(box.read(BoxName.carYear).toString()) > 2023
              ? AnimatedContainer(
                  duration: const Duration(microseconds: 200),
                  width: controller.widthMapTypeAndTraffic,
                  decoration: BoxDecoration(
                      color: AppColor.secondaryColor,
                      border: Border.all(color: AppColor.blueColor),
                      borderRadius: BorderRadius.circular(15)),
                  child: Builder(builder: (context) {
                    return IconButton(
                      onPressed: () async {
                        // mySnakeBarError('ad');
                        Get.to(() => const VipOrderPage());
                      },
                      icon: const Icon(
                        Octicons.watch,
                        size: 29,
                        color: AppColor.blueColor,
                      ),
                    );
                  }),
                )
              : const SizedBox(),
          // const SizedBox(
          //   height: 5,
          // ),

          AnimatedContainer(
            duration: const Duration(microseconds: 200),
            width: controller.widthMapTypeAndTraffic,
            decoration: BoxDecoration(
                color: AppColor.secondaryColor,
                border: Border.all(color: AppColor.blueColor),
                borderRadius: BorderRadius.circular(15)),
            child: Builder(builder: (context) {
              return IconButton(
                onPressed: () async {
                  box.remove(BoxName.agreeTerms);
                  Get.to(() => const NavigationView());

                  // box.write(BoxName.statusDriverLocation, 'off');
                },
                icon: const Icon(
                  FontAwesome5.map,
                  size: 29,
                  color: AppColor.blueColor,
                ),
              );
            }),
          ),
          // AnimatedContainer(
          //   duration: const Duration(microseconds: 200),
          //   width: controller.widthMapTypeAndTraffic,
          //   decoration: BoxDecoration(
          //       color: AppColor.secondaryColor,
          //       border: Border.all(color: AppColor.blueColor),
          //       borderRadius: BorderRadius.circular(15)),
          //   child: Builder(builder: (context) {
          //     return IconButton(
          //       onPressed: () async {
          //         NotificationService.sendNotification(
          //           target: 'service', // الإرسال لجميع المشتركين في "service"
          //           title: 'طلب خدمة جديد',
          //           body: 'تم استلام طلب خدمة جديد. الرجاء مراجعة التفاصيل.',
          //           isTopic: true,
          //           category: 'new_service_request', // فئة توضح نوع الإشعار
          //         );
          //       },
          //       icon: const Icon(
          //         FontAwesome5.grin_tears,
          //         size: 29,
          //         color: AppColor.blueColor,
          //       ),
          //     );
          //   }),
          // ),

          const SizedBox(
            height: 5,
          ),
        ],
      ),
    ),
  );
}

Future<void> checkForPendingOrderFromServer() async {
  bool _isProcessingOrder = false;
  if (_isProcessingOrder) return;

  final driverId = box.read(BoxName.driverID)?.toString();
  if (driverId == null) return; // Can't check without a driver ID

  _isProcessingOrder = true; // Lock

  try {
    // You need to create this CRUD method
    var response = await CRUD().post(
      link: AppLink.getArgumentAfterAppliedFromBackground,
      payload: {'driver_id': driverId},
    );
    Log.print('response: ${response}');

    // Assuming the server returns order data if found, or 'failure'/'none' if not
    if (response['status'] == 'success') {
      final Map<String, dynamic> orderInfoFromServer = response['message'];
      final Map<String, dynamic> rideArguments =
          _transformServerDataToAppArguments(orderInfoFromServer);
      // 2. Build the new arguments map, matching your Flutter structure

/////////////
      final customerToken = (response)['message']['token_passenger'];
      final orderId = (response)['message']['ride_id'].toString();
      box.write(BoxName.rideArgumentsFromBackground, rideArguments);
      box.write(BoxName.statusDriverLocation, 'on');
      box.write(BoxName.rideStatus, 'Apply');
      Get.put(OrderRequestController()).changeApplied();
      // MyDialog().getDialog(orderId.toString(), customerToken, () {});

      // Now proceed with the UI flow
      // _sendAcceptanceNotification(customerToken, orderId.toString());
      // await _bringAppToForegroundAndNavigate(orderId);
      Get.to(() => PassengerLocationMapPage(),
          arguments: box.read(BoxName.rideArgumentsFromBackground));
    } else {
      box.write(BoxName.rideArgumentsFromBackground, 'failure');
    }
  } catch (e) {
  } finally {
    _isProcessingOrder = false; // Release lock
  }
}

Map<String, dynamic> _transformServerDataToAppArguments(
    Map<String, dynamic> serverData) {
  // Helper function to safely get and convert values to String
  String _getString(String key, [String defaultValue = 'unknown']) {
    // serverData[key] might be an int, double, or string. .toString() handles all.
    // If it's null, use the default value.
    return serverData[key]?.toString() ?? defaultValue;
  }

  return {
    'passengerLocation': _getString('passenger_location'),
    'passengerDestination': _getString('passenger_destination'),
    'Duration': _getString('duration'),
    'totalCost': _getString('total_cost'),
    'Distance': _getString('distance'),
    'name': _getString('name'),
    'phone': _getString('phone'),
    'email': _getString('email'),
    'tokenPassenger': _getString('token_passenger'),
    'direction': _getString('direction_url'),
    'DurationToPassenger': _getString('duration_to_passenger'),
    'rideId': _getString('ride_id'),
    'passengerId': _getString('passenger_id'),
    'driverId': _getString('driver_id'),
    'durationOfRideValue': _getString('duration_of_ride'),
    'paymentAmount': _getString('payment_amount'),
    'paymentMethod': _getString('payment_method'),
    'passengerWalletBurc': _getString('passenger_wallet_burc'),
    'timeOfOrder': _getString('time_of_order'),
    'totalPassenger': _getString('total_passenger'),
    'carType': _getString('car_type'),
    'kazan': _getString('kazan'),
    'startNameLocation': _getString('start_name_location'),
    'endNameLocation': _getString('end_name_location'),

    // --- Special Handling ---

    // Steps (handle null values by providing an empty string)
    'step0': _getString('step0'),
    'step1': _getString('step1'),
    'step2': _getString('step2'),
    'step3': _getString('step3'),
    'step4': _getString('step4'),

    // Boolean conversion (1/0 from server to 'true'/'false' string for the app)
    'WalletChecked': (serverData['wallet_checked'] == 1).toString(),

    // Logic-based conversion for isHaveSteps
    // Your app's `rideArguments` expects 'startEnd', so we provide that if has_steps is 1.
    // You might need to adjust this logic if 'haveSteps' is also a possibility.
    'isHaveSteps': (serverData['has_steps'] == 1)
        ? 'startEnd'
        : 'noSteps', // Providing a default
  };
}

void _sendAcceptanceNotification(String? customerToken, rideId) {
  try {
    if (customerToken == null) return;

    List<String> bodyToPassenger = [
      box.read(BoxName.driverID).toString(),
      box.read(BoxName.nameDriver).toString(),
      box.read(BoxName.tokenDriver).toString(),
      rideId.toString()
    ];

    // Safely check for customer token
    final String? token = customerToken;
    if (token != null && token.isNotEmpty) {
      NotificationService.sendNotification(
        target: token.toString(),
        title: 'Accepted Ride'.tr,
        body: 'your ride is Accepted'.tr,
        isTopic: false, // Important: this is a token
        tone: 'start',
        driverList: bodyToPassenger, category: 'Accepted Ride',
      );
    } else {}
  } catch (e) {}
}
