// import 'dart:io';

// import 'package:bubble_head/bubble.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter_font_icons/flutter_font_icons.dart';
// import 'package:get/get.dart';
// import 'package:sefer_driver/constant/info.dart';
// import 'package:sefer_driver/controller/functions/location_controller.dart';
// import 'package:sefer_driver/views/widgets/elevated_btn.dart';
// import 'package:sefer_driver/views/widgets/my_textField.dart';
// import 'package:url_launcher/url_launcher.dart';

// import '../../../../constant/box_name.dart';
// import '../../../../constant/colors.dart';
// import '../../../../constant/style.dart';
// import '../../../../controller/functions/launch.dart';
// import '../../../../controller/home/captin/map_driver_controller.dart';
// import '../../../../main.dart';

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

//   @override
//   Widget build(BuildContext context) {
//     return GetBuilder<MapDriverController>(
//       builder: (mapDriverController) => mapDriverController.isRideStarted
//           ? Positioned(
//               left: 16,
//               bottom: 16,
//               child: Card(
//                 elevation: 4,
//                 shape: RoundedRectangleBorder(
//                   borderRadius: BorderRadius.circular(12),
//                 ),
//                 child: SizedBox(
//                   height: 60,
//                   width: 180,
//                   child: Row(
//                     mainAxisAlignment: MainAxisAlignment.spaceAround,
//                     children: [
//                       IconButton(
//                         onPressed: () {
//                           _handleSosCall(mapDriverController);
//                         },
//                         icon: const Icon(
//                           Icons.sos_sharp,
//                           size: 32,
//                           color: AppColor.redColor,
//                         ),
//                         tooltip: 'SOS - Call Emergency',
//                       ),
//                       VerticalDivider(
//                         color: Colors.grey[300],
//                         thickness: 1,
//                       ),
//                       IconButton(
//                         onPressed: () {
//                           _handleWhatsApp(mapDriverController);
//                         },
//                         icon: const Icon(
//                           FontAwesome.whatsapp,
//                           color: AppColor.greenColor,
//                           size: 32,
//                         ),
//                         tooltip: 'SOS - Send WhatsApp Message',
//                       ),
//                       VerticalDivider(
//                         color: Colors.grey[300],
//                         thickness: 1,
//                       ),
//                       IconButton(
//                         onPressed: () {
//                           _handleGoogleMap(mapDriverController);
//                         },
//                         icon: const Icon(
//                           MaterialCommunityIcons.map_marker_radius,
//                           color: AppColor.primaryColor,
//                           size: 32,
//                         ),
//                         tooltip: 'Google Maps - Navigate',
//                       ),
//                     ],
//                   ),
//                 ),
//               ),
//             )
//           : const SizedBox(),
//     );
//   }

//   void _handleSosCall(MapDriverController mapDriverController) {
//     if (box.read(BoxName.sosPhoneDriver) == null) {
//       Get.defaultDialog(
//         title: 'Insert Emergency Number'.tr,
//         content: Form(
//           key: mapDriverController.formKey1,
//           child: MyTextForm(
//             controller: mapDriverController.sosEmergincyNumberCotroller,
//             label: 'Emergency Number'.tr,
//             hint: 'Enter phone number'.tr,
//             type: TextInputType.phone,
//           ),
//         ),
//         confirm: MyElevatedButton(
//           title: 'Save'.tr,
//           onPressed: () {
//             if (mapDriverController.formKey1.currentState!.validate()) {
//               box.write(BoxName.sosPhoneDriver,
//                   mapDriverController.sosEmergincyNumberCotroller.text);
//               Get.back(); // Close the dialog
//               launchCommunication(
//                   'phone', box.read(BoxName.sosPhoneDriver), '');
//             }
//           },
//         ),
//       );
//     } else {
//       launchCommunication('phone', box.read(BoxName.sosPhoneDriver), '');
//     }
//   }

//   void _handleWhatsApp(MapDriverController mapDriverController) {
//     if (box.read(BoxName.sosPhoneDriver) == null) {
//       Get.defaultDialog(
//         title: 'Insert Emergency Number'.tr,
//         content: Form(
//           key: mapDriverController.formKey1,
//           child: MyTextForm(
//             controller: mapDriverController.sosEmergincyNumberCotroller,
//             label: 'Emergency Number'.tr,
//             hint: 'Enter phone number'.tr,
//             type: TextInputType.phone,
//           ),
//         ),
//         confirm: MyElevatedButton(
//           title: 'Save'.tr,
//           onPressed: () {
//             if (mapDriverController.formKey1.currentState!.validate()) {
//               box.write(BoxName.sosPhoneDriver,
//                   mapDriverController.sosEmergincyNumberCotroller.text);
//               Get.back(); // Close the dialog
//               _sendWhatsAppMessage(mapDriverController);
//             }
//           },
//         ),
//       );
//     } else {
//       _sendWhatsAppMessage(mapDriverController);
//     }
//   }

//   void _handleGoogleMap(MapDriverController mapDriverController) {
//     () async {
//       if (Platform.isAndroid) {
//         Bubble().startBubbleHead(sendAppToBackground: true);
//       }
//       var startLat =
//           Get.find<MapDriverController>().latLngPassengerLocation.latitude;
//       var startLng =
//           Get.find<MapDriverController>().latLngPassengerLocation.longitude;

//       var endLat =
//           Get.find<MapDriverController>().latLngPassengerDestination.latitude;
//       var endLng =
//           Get.find<MapDriverController>().latLngPassengerDestination.longitude;

//       String url =
//           'https://www.google.com/maps/dir/$startLat,$startLng/$endLat,$endLng/&directionsmode=driving';
//       if (await canLaunchUrl(Uri.parse(url))) {
//         await launchUrl(Uri.parse(url));
//       } else {
//         throw 'Could not launch google maps';
//       }
//     }();
//   }

//   void _sendWhatsAppMessage(MapDriverController mapDriverController) {
//     final sosNumber = box.read(BoxName.sosPhoneDriver);
//     if (sosNumber != null) {
//       launchCommunication(
//         'whatsapp',
//         '+2$sosNumber', // Consider international format
//         "${"Hello, this is Driver".tr} ${box.read(BoxName.nameDriver)}. "
//             "${"My current location is:".tr} "
//             "https://www.google.com/maps/place/"
//             "${Get.find<LocationController>().myLocation.latitude},"
//             "${Get.find<LocationController>().myLocation.longitude} "
//             "${"\nI have a trip on".tr} ${AppInformation.appName} "
//             "${"app with passenger".tr} ${mapDriverController.passengerName}.",
//       );
//     }
//   }
// }

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:sefer_driver/views/widgets/my_textField.dart';

import '../../../../constant/box_name.dart';
import '../../../../constant/colors.dart';
import '../../../../constant/style.dart';
import '../../../../controller/firebase/firbase_messge.dart';
import '../../../../controller/functions/launch.dart';
import '../../../../controller/home/captin/map_driver_controller.dart';
import '../../../../main.dart';

// Changed: إعادة تصميم وتغيير موضع أزرار التواصل والطوارئ
class SosConnect extends StatelessWidget {
  const SosConnect({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapDriverController>(
      builder: (controller) {
        // New: تجميع الأزرار في عمود واحد على الجانب الأيمن
        return Positioned(
          bottom: 110, // New: فوق عداد السرعة
          right: 16,
          child: Column(
            children: [
              // زر الاتصال بالراكب (يظهر قبل بدء الرحلة)
              if (!controller.isRideBegin && controller.isPassengerInfoWindow)
                _buildSocialButton(
                  icon: Icons.phone,
                  color: AppColor.blueColor,
                  tooltip: 'Call Passenger',
                  onPressed: () async {
                    controller.isSocialPressed = true;
                    await controller.driverCallPassenger();
                    makePhoneCall(controller.passengerPhone.toString());
                  },
                ),

              // زر الرسائل للراكب (يظهر قبل بدء الرحلة)
              if (!controller.isRideBegin && controller.isPassengerInfoWindow)
                const SizedBox(height: 12),
              if (!controller.isRideBegin && controller.isPassengerInfoWindow)
                _buildSocialButton(
                  icon: Icons.message,
                  color: AppColor.greenColor,
                  tooltip: 'Send Message',
                  onPressed: () {
                    // الكود الخاص بنافذة الرسائل السريعة
                    _showMessageOptions(context, controller);
                  },
                ),

              // زر الطوارئ (SOS) (يظهر بعد بدء الرحلة)
              if (controller.isRideStarted)
                _buildSocialButton(
                  icon: Icons.sos_sharp,
                  color: AppColor.redColor,
                  tooltip: 'SOS - Call Emergency',
                  onPressed: () => _handleSosCall(controller),
                ),
            ],
          ),
        );
      },
    );
  }

  // New: ودجت منفصل لبناء أزرار التواصل
  Widget _buildSocialButton(
      {required IconData icon,
      required Color color,
      required String tooltip,
      required VoidCallback onPressed}) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.white,
        boxShadow: [BoxShadow(blurRadius: 5, color: Colors.black26)],
      ),
      child: IconButton(
        icon: Icon(icon, color: color, size: 28),
        tooltip: tooltip,
        onPressed: onPressed,
      ),
    );
  }

  // الكود الخاص بنافذة إدخال رقم الطوارئ
  void _handleSosCall(MapDriverController mapDriverController) {
    if (box.read(BoxName.sosPhoneDriver) == null) {
      Get.defaultDialog(
        title: 'Insert Emergency Number'.tr,
        content: Form(
          key: mapDriverController.formKey1,
          child: MyTextForm(
            controller: mapDriverController.sosEmergincyNumberCotroller,
            label: 'Emergency Number'.tr,
            hint: 'Enter phone number'.tr,
            type: TextInputType.phone,
          ),
        ),
        confirm: MyElevatedButton(
          title: 'Save'.tr,
          onPressed: () {
            if (mapDriverController.formKey1.currentState!.validate()) {
              box.write(BoxName.sosPhoneDriver,
                  mapDriverController.sosEmergincyNumberCotroller.text);
              Get.back();
              launchCommunication(
                  'phone', box.read(BoxName.sosPhoneDriver), '');
            }
          },
        ),
      );
    } else {
      launchCommunication('phone', box.read(BoxName.sosPhoneDriver), '');
    }
  }

  // New: الكود الخاص بنافذة الرسائل السريعة (مستخرج من passenger_info_window.dart)
  void _showMessageOptions(
      BuildContext context, MapDriverController controller) {
    Get.bottomSheet(
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      Padding(
        padding: const EdgeInsets.all(16.0),
        child: _buildMessageOptions(controller),
      ),
    );
  }

  Widget _buildMessageOptions(MapDriverController controller) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Select a quick message'.tr, style: AppStyle.title),
        const SizedBox(height: 16),
        _buildMessageTile(
            text: "Where are you, sir?".tr,
            onTap: () {
              Get.find<FirebaseMessagesController>()
                  .sendNotificationToDriverMAP(
                      'message From Driver',
                      "Where are you, sir?".tr,
                      controller.tokenPassenger,
                      [],
                      'ding.wav');
              Get.back();
            }),
        _buildMessageTile(
            text: "I've been trying to reach you but your phone is off.".tr,
            onTap: () {
              Get.find<FirebaseMessagesController>()
                  .sendNotificationToDriverMAP(
                      'message From Driver',
                      "I've been trying to reach you but your phone is off.".tr,
                      controller.tokenPassenger,
                      [],
                      'ding.wav');
              Get.back();
            }),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: Form(
                key: controller.formKey2,
                child: MyTextForm(
                  controller: controller.messageToPassenger,
                  label: 'Type something'.tr,
                  hint: 'Type something'.tr,
                  type: TextInputType.text,
                ),
              ),
            ),
            IconButton(
              onPressed: () {
                Get.find<FirebaseMessagesController>()
                    .sendNotificationToDriverMAP(
                        'message From Driver',
                        controller.messageToPassenger.text,
                        controller.tokenPassenger,
                        [],
                        'ding.wav');
                controller.messageToPassenger.clear();
                Get.back();
              },
              icon: const Icon(Icons.send),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildMessageTile(
      {required String text, required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(12),
        margin: const EdgeInsets.symmetric(vertical: 4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.grey[100],
        ),
        child: Text(text, style: AppStyle.title),
      ),
    );
  }
}
