import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';
import 'package:siro_driver/views/widgets/my_textField.dart';
import 'package:siro_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/links.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) {
        bool showSos = controller.isRideStarted;

        if (!showSos) return const SizedBox();

        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: [
              // === SOS Button ===
              _buildModernActionButton(
                icon: MaterialIcons.warning,
                color: Colors.white,
                bgColor: AppColor.redColor,
                tooltip: 'EMERGENCY SOS',
                isPulsing: true,
                onTap: () => _handleSosCall(controller),
              ),
              const SizedBox(height: 8),
              // === Quick Invite Button ===
              _buildModernActionButton(
                icon: Icons.qr_code_rounded,
                color: Colors.white,
                bgColor: AppColor.blueColor,
                tooltip: 'Quick Invite',
                isPulsing: false,
                onTap: () => _showQuickInviteDialog(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: '0923456789',
                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 _showQuickInviteDialog(MapDriverController controller) {
    // In a real scenario, this code would be fetched from the backend (ReferralController)
    // For now we will use a generated code or driverId. We should use the one from ReferralController
    // But since we are accessing it globally, we can just use the driverID + 123 for now until it's linked
    String driverId = box.read(BoxName.driverID).toString();
    String inviteCode = "SR$driverId"; // Placeholder code
    String deepLink = "https://${AppLink.appDomain}/invite?ref=$inviteCode";

    Get.defaultDialog(
      title: "Quick Invite".tr,
      titleStyle: AppStyle.title.copyWith(fontWeight: FontWeight.bold),
      content: Column(
        children: [
          Text(
            "Let the passenger scan this code to sign up".tr,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 14, color: Colors.grey),
          ),
          const SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: QrImageView(
              data: deepLink,
              version: QrVersions.auto,
              size: 200.0,
              backgroundColor: Colors.white,
            ),
          ),
          const SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            decoration: BoxDecoration(
              color: AppColor.blueColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: AppColor.blueColor.withOpacity(0.3)),
            ),
            child: Text(
              inviteCode,
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.w900,
                color: AppColor.blueColor,
                letterSpacing: 4,
              ),
            ),
          ),
        ],
      ),
      confirm: MyElevatedButton(
        title: 'Done'.tr,
        onPressed: () => Get.back(),
      ),
    );
  }
}
