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

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

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapDriverController>(
      id: 'SosConnect', // Keep ID for updates
      builder: (controller) {
        // Check visibility logic
        bool showPassengerContact =
            !controller.isRideBegin && controller.isPassengerInfoWindow;
        bool showSos = controller.isRideStarted;

        if (!showPassengerContact && !showSos) return const SizedBox();

        // REMOVED: Positioned widget
        return Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.95),
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // === Call Button ===
              if (showPassengerContact)
                _buildModernActionButton(
                  icon: Icons.phone_in_talk,
                  color: Colors.white,
                  bgColor: AppColor.blueColor,
                  tooltip: 'Call Passenger',
                  onTap: () async {
                    controller.isSocialPressed = true;
                    bool canCall = await controller.driverCallPassenger();
                    if (canCall) {
                      makePhoneCall(controller.passengerPhone.toString());
                    } else {
                      mySnackeBarError("Policy restriction on calls".tr);
                    }
                  },
                ),

              if (showPassengerContact) const SizedBox(height: 12),

              // === Message Button ===
              if (showPassengerContact)
                _buildModernActionButton(
                  icon: MaterialCommunityIcons.message_text_outline,
                  color: AppColor.primaryColor,
                  bgColor: Colors.grey.shade100,
                  tooltip: 'Message Passenger',
                  onTap: () => _showMessageOptions(context, controller),
                ),

              // === SOS Button ===
              if (showSos)
                _buildModernActionButton(
                  icon: MaterialIcons.warning,
                  color: Colors.white,
                  bgColor: AppColor.redColor,
                  tooltip: 'EMERGENCY SOS',
                  isPulsing: true,
                  onTap: () => _handleSosCall(controller),
                ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildModernActionButton({
    required IconData icon,
    required Color color,
    required Color bgColor,
    required String tooltip,
    required VoidCallback onTap,
    bool isPulsing = false,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Container(
          width: 48,
          height: 48,
          decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.circular(12),
            boxShadow: isPulsing
                ? [
                    BoxShadow(
                      color: bgColor.withOpacity(0.4),
                      blurRadius: 12,
                      spreadRadius: 2,
                    )
                  ]
                : [],
          ),
          child: Icon(icon, color: color, size: 24),
        ),
      ),
    );
  }

  // --- Logic Functions ---
  void _handleSosCall(MapDriverController mapDriverController) {
    if (box.read(BoxName.sosPhoneDriver) == null) {
      Get.defaultDialog(
        title: 'Emergency Contact'.tr,
        content: Column(
          children: [
            Text('Please enter the emergency number.'.tr),
            Form(
              key: mapDriverController.formKey1,
              child: MyTextForm(
                controller: mapDriverController.sosEmergincyNumberCotroller,
                label: 'Phone Number'.tr,
                hint: '01xxxxxxxxx',
                type: TextInputType.phone,
              ),
            ),
          ],
        ),
        confirm: MyElevatedButton(
          title: 'Save & Call'.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), '');
    }
  }

  void _showMessageOptions(
      BuildContext context, MapDriverController controller) {
    Get.bottomSheet(
      Container(
        padding: const EdgeInsets.all(20),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(25)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Quick Messages'.tr,
                style:
                    const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 15),
            _buildQuickMessageItem("Where are you, sir?".tr, controller),
            _buildQuickMessageItem("I've arrived.".tr, controller),
            const Divider(),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: controller.messageToPassenger,
                    decoration:
                        InputDecoration(hintText: 'Type a message...'.tr),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: () {
                    _sendMessage(controller, controller.messageToPassenger.text,
                        'cancel');
                    controller.messageToPassenger.clear();
                    Get.back();
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildQuickMessageItem(String text, MapDriverController controller) {
    return ListTile(
      title: Text(text),
      onTap: () {
        _sendMessage(controller, text, 'ding');
        Get.back();
      },
    );
  }

  void _sendMessage(MapDriverController controller, String body, String tone) {
    NotificationService.sendNotification(
      target: controller.tokenPassenger.toString(),
      title: 'Driver Message'.tr,
      body: body,
      isTopic: false,
      tone: tone,
      driverList: [],
      category: 'message From Driver',
    );
  }
}
