import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:service/views/widgets/elevated_btn.dart';

import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/widgets/mycircular.dart';
import '../functions/crud.dart';
import '../functions/image.dart';
import '../functions/launch.dart';

enum DocumentType {
  carLicenseFront,
  carLicenseBack,
  idCardFront,
  nonIdCardFront,
  nonIdCardBack,
  idCardBack,
  driverLicense,
  unknown,
}

class RegisterCaptainController extends GetxController {
  bool isDriverSaved = false;
  bool isCarSaved = false;
  Map<String, dynamic>? arguments;
  String? driverId;
  String? email;
  String? phone;
  bool isEgypt = true;

  @override
  void onInit() {
    super.onInit();
    arguments = Get.arguments;

    getPrompt();

    initArguments();
  }

  void driveInit() {
    arguments = Get.arguments;
    initArguments();
  }

  changeNationality() {
    isEgypt = !isEgypt;
    update();
  }


  void initArguments() {
    if (arguments != null) {
      driverId = arguments!['driverId'];
      email = arguments!['email'];
      phone = arguments!['phone_number'];
    } else {
      print('Arguments are null');
    }
  }

  Map<String, dynamic> responseMap = {};
  Map<String, dynamic> responseCarLicenseMapJordan = {};
  Map<String, dynamic> responseBackCarLicenseMap = {};
  Map<String, dynamic> responseIdCardMap = {};
  Map<String, dynamic> responseIdCardDriverEgyptBack = {};
  Map<String, dynamic> responseForComplaint = {};
  Map<String, dynamic> responseIdCardDriverEgyptFront = {};
  Map<String, dynamic> responseIdEgyptFront = {};
  Map<String, dynamic> responseCriminalRecordEgypt = {};
  Map<String, dynamic> responseIdEgyptBack = {};
  Map<String, dynamic> responseNonIdCardFront = {};
  Map<String, dynamic> responseNonIdCardBack = {};
  Map<String, dynamic> responseIdEgyptDriverLicense = {};
  String? responseIdCardDriverEgypt1;
  bool isloading = false;
  var image;
  DateTime now = DateTime.now();

  bool isLoading = false;
  String getExpectedDocument(String imagePath) {
    switch (imagePath) {
      case 'car_front':
        return 'car_license_front'.tr;
      case 'car_back':
        return 'car_license_back'.tr;
      case 'id_back':
        return 'id_card_back'.tr;
      case 'id_front':
        return 'id_card_front'.tr;
      case 'driver_license':
        return 'driver_license'.tr;
      default:
        return 'unknown_document'.tr;
    }
  }

  DocumentType getExpectedType(String imagePath) {
    switch (imagePath) {
      case 'car_front':
        return DocumentType.carLicenseFront;
      case 'car_back':
        return DocumentType.carLicenseBack;
      case 'id_back':
        return DocumentType.idCardBack;
      case 'id_front':
        return DocumentType.idCardFront;
      case 'driver_license':
        return DocumentType.driverLicense;
      default:
        return DocumentType.unknown;
    }
  }

  String getDetectedDocument(DocumentType type) {
    switch (type) {
      case DocumentType.carLicenseFront:
        return 'car_license_front'.tr;
      case DocumentType.carLicenseBack:
        return 'car_license_back'.tr;
      case DocumentType.idCardFront:
        return 'id_card_front'.tr;
      case DocumentType.idCardBack:
        return 'id_card_back'.tr;
      case DocumentType.driverLicense:
        return 'driver_license'.tr;
      default:
        return 'unknown_document'.tr;
    }
  }

  DocumentType checkDocumentType(String text) {
    // Convert text to lowercase and remove all spaces and new lines
    text = text.toLowerCase().replaceAll(RegExp(r'\s+'), '');

    // Keywords for each document type
    final Map<DocumentType, List<String>> keywords = {
      DocumentType.carLicenseBack: ['شاسيه', 'موتور', 'سم٣'],
      DocumentType.carLicenseFront: ['رخصةتسيير'],
      DocumentType.idCardFront: [
        'بطاقةتحقيقالشخصية',
        'بطاقة تحقيق الشخصية',
        'تحقيق'
      ],
      DocumentType.idCardBack: ['البطاقةساريةحتى'],
      DocumentType.driverLicense: ['قيادةخاصة', 'خاصه', 'قيادة'],
    };

    // Check each document type
    for (var entry in keywords.entries) {
      if (entry.value.any((keyword) => text.contains(keyword))) {
        return entry.key;
      }
    }

    // If no match is found
    return DocumentType.unknown;
  }

  List prompts = [];
  getPrompt() async {
    var res = await CRUD()
        .get(link: AppLink.getPromptDriverDocumentsEgypt, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      prompts = d;
    } else {}
  }

  Future allMethodForAI(String prompt, imagePath, driverID) async {
    isLoading = true;
    update();
    await ImageController()
        .choosImage(AppLink.uploadEgypt, driverID, imagePath);

    var extractedString = await CRUD().arabicTextExtractByVisionAndAI(
        imagePath: imagePath, driverID: driverID);
    var json = jsonDecode(extractedString);
    var textValues = extractTextFromLines(json);
    Log.print('textValues: ${textValues}');
    // await Get.put(AI()).geminiAiExtraction(prompt, textValues, imagePath);

    DocumentType detectedType = checkDocumentType(textValues);
    String expectedDocument = getExpectedDocument(imagePath);
    String detectedDocument = getDetectedDocument(detectedType);

    // bool isCorrectDocument = (detectedType == getExpectedType(imagePath));
    // if (!isCorrectDocument) {
    //   Get.defaultDialog(
    //       title: 'incorrect_document_title'.tr,
    //       middleText:
    //           '${'expected'.tr}: $expectedDocument\n${'detected'.tr}: $detectedDocument',
    //       confirm: MyElevatedButton(
    //           title: 'OK'.tr,
    //           onPressed: () {
    //             Get.back();
    //           }));
    // } else {
    // Process the correct document
    await anthropicAI(textValues, prompt, imagePath);
    // }
    isLoading = false;
    update();
  }

  String extractTextFromLines(Map<String, dynamic> jsonData) {
    final readResult = jsonData['readResult'];
    final blocks = readResult['blocks'];

    final StringBuffer buffer = StringBuffer();

    for (final block in blocks) {
      final lines = block['lines'];
      for (final line in lines) {
        final text = line['text'];
        buffer.write(text);
        buffer.write('\n');
      }
    }

    return buffer.toString().trim();
  }

  List driverNotCompleteRegistration = [];
  getDriverNotCompleteRegistration() async {
    var res = await CRUD()
        .get(link: AppLink.getDriverNotCompleteRegistration, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      driverNotCompleteRegistration = d;
      update();
    } else {
      Get.snackbar(res, '');
    }
  }

  final today = DateTime.now();

  Future<void> addDriverAndCarEgypt() async {
    final expiryDate = responseIdEgyptDriverLicense['expiry_date'];
    final expiryDateTime = DateTime.tryParse(expiryDate);
    Log.print('expiryDateTime: ${expiryDateTime}');
    final isExpired = expiryDateTime != null && expiryDateTime.isBefore(today);

    final taxExpiryDate = responseIdCardDriverEgyptBack['tax_expiry'];
    Log.print('taxExpiryDate: ${taxExpiryDate}');

    // Get the inspection date from the response
    final inspectionDate = responseIdCardDriverEgyptBack['inspection_date'];
    final year = int.parse(inspectionDate.split('-')[0]);
    // Try parsing the tax expiry date. If it fails, set it to null.
    final taxExpiryDateTime = DateTime.tryParse(taxExpiryDate ?? '');
    Log.print('taxExpiryDateTime: ${taxExpiryDateTime}');
    final isExpiredCar =
        taxExpiryDateTime != null && taxExpiryDateTime.isBefore(today);

    // Check if the inspection date is before today
    final inspectionDateTime = DateTime(year, 12, 31);
    final isInspectionExpired = inspectionDateTime.isBefore(today);

    if (isExpiredCar || isInspectionExpired) {
      Get.defaultDialog(
        title: 'Expired Driver’s License'.tr,
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.warning, size: 48, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              "Your driver’s license and/or car tax has expired. Please renew them before proceeding."
                  .tr,
              textAlign: TextAlign.center,
              style: AppStyle.title,
            ),
            const SizedBox(height: 16),
            IconButton(
              onPressed: () async {
                // await Get.find<TextToSpeechController>().speakText(
                //   'Your driver’s license and/or car tax has expired. Please renew them before proceeding.'
                //       .tr,
                // );
              },
              icon: const Icon(Icons.volume_up),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
            },
            child: const Text('OK'),
          ),
        ],
      );
    } else if (isExpired) {
      Get.defaultDialog(
        title: 'Expired Driver’s License'.tr,
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.warning, size: 48, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              "Your driver’s license has expired. Please renew it before proceeding."
                  .tr,
              textAlign: TextAlign.center,
              style: AppStyle.title,
            ),
            const SizedBox(height: 16),
            IconButton(
              onPressed: () async {
                // await Get.find<TextToSpeechController>().speakText(
                //   'Your driver’s license has expired. Please renew it before proceeding.'
                //       .tr,
                // );
              },
              icon: const Icon(Icons.volume_up),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
            },
            child: const Text('OK'),
          ),
        ],
      );
    }
    // else if (responseIdEgyptDriverLicense['national_number']
    //         .toString()
    //         .substring(0, 12) !=
    //     responseIdEgyptBack['nationalID'].toString().substring(0, 12)) {
    //   Get.defaultDialog(
    //     barrierDismissible: false,
    //     title: 'ID Mismatch',
    //     content: Column(
    //       mainAxisSize: MainAxisSize.min,
    //       children: [
    //         const Icon(Icons.warning, size: 48, color: Colors.red),
    //         const SizedBox(height: 16),
    //         Text(
    //           "The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents."
    //               .tr,
    //           textAlign: TextAlign.center,
    //           style: AppStyle.title,
    //         ),
    //         const SizedBox(height: 16),
    //         IconButton(
    //           onPressed: () async {
    //             // await Get.find<TextToSpeechController>().speakText(
    //             //   'The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents.',
    //             // );
    //           },
    //           icon: const Icon(Icons.volume_up),
    //         ),
    //       ],
    //     ),
    //     actions: [
    //       TextButton(
    //         onPressed: () {
    //           Get.back();
    //         },
    //         child: const Text('OK'),
    //       ),
    //     ],
    //   );
    // }
    // else if (responseCriminalRecordEgypt['FullName'] !=
    //     responseIdEgyptDriverLicense['name_arabic']) {
    //   Get.defaultDialog(
    //     barrierDismissible: false,
    //     title: 'Criminal Record Mismatch',
    //     content: Column(
    //       mainAxisSize: MainAxisSize.min,
    //       children: [
    //         const Icon(Icons.warning, size: 48, color: Colors.red),
    //         const SizedBox(height: 16),
    //         Text(
    //           'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
    //               .tr,
    //           textAlign: TextAlign.center,
    //           style: AppStyle.title,
    //         ),
    //         const SizedBox(height: 16),
    //         IconButton(
    //           onPressed: () async {
    //             await Get.find<TextToSpeechController>().speakText(
    //               'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
    //                   .tr,
    //             );
    //           },
    //           icon: const Icon(Icons.volume_up),
    //         ),
    //       ],
    //     ),
    //     actions: [
    //       TextButton(
    //         onPressed: () {
    //           Get.back();
    //         },
    //         child: const Text('OK'),
    //       ),
    //     ],
    //   );
    // }
    else {
      await addDriverEgypt();
      await addRegistrationCarEgypt();

      if (isCarSaved && isDriverSaved) {
        Get.snackbar('added', '',
            backgroundColor:
                AppColor.greenColor); // Get.offAll(() => HomeCaptain());
        // Get.offAll(() => HomeCaptain());
      }
    }
  }

  String extractDOB(String nationalNumber) {
    if (nationalNumber.length != 14) {
      Get.snackbar('National number must be 14 digits long.', 'message',
          backgroundColor: AppColor.redColor);
      throw ArgumentError('National number must be 14 digits long.');
    }

    // Extract the first digit to determine the century
    String firstDigit = nationalNumber[0];

    // Extract year, month, and day parts
    String yearPart = nationalNumber.substring(1, 3);
    String monthPart = nationalNumber.substring(3, 5);
    String dayPart = nationalNumber.substring(5, 7);

    // Determine the year based on the first digit
    int yearPrefix;
    if (firstDigit == '2') {
      yearPrefix = 1900;
    } else if (firstDigit == '3') {
      yearPrefix = 2000;
    } else {
      throw ArgumentError('Invalid first digit in national number.');
    }

    // Construct the full year
    int year = yearPrefix + int.parse(yearPart);

    // Format the date as YYYY-MM-DD
    String dob =
        '$year-${monthPart.padLeft(2, '0')}-${dayPart.padLeft(2, '0')}';

    return dob;
  }

  String generatePassword({int length = 8}) {
    const String upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const String lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
    const String digits = '0123456789';
    const String specialCharacters = '!@#\$%^&*()-_=+[]{}|;:,.<>?';

    const String allChars =
        upperCaseLetters + lowerCaseLetters + digits + specialCharacters;
    final Random random = Random();

    // Generate a random password of the specified length
    String password = List.generate(length, (index) {
      int randomIndex = random.nextInt(allChars.length);
      return allChars[randomIndex];
    }).join();

    return password;
  }

  Future<void> addDriverForeign() async {
    isLoading = true;
    update();
    var added = await storage.read(key: 'name');
    String newPassword = generatePassword();
    print('Generated Password: $newPassword');
    var payload = {
      'first_name':
          responseNonIdCardFront['full_name']?.toString().split(' ')[0] ??
              'Not specified',
      'last_name':
          responseNonIdCardFront['full_name']?.toString().split(' ').last ??
              'Not specified',
      'email': box.read(BoxName.emailDriver)?.toString() ?? 'Not specified',
      'phone': box.read(BoxName.phoneDriver)?.toString() ?? 'Not specified',
      'id': box.read(BoxName.driverID)?.toString() ?? 'Not specified',
      'password': newPassword.toString() ?? '123456',
      'gender': responseNonIdCardFront['gender']?.toString() ?? 'Not specified',
      'license_type': 'Foreign',
      'national_number':
          responseNonIdCardFront['passport_no']?.toString() ?? 'Not specified',
      'name_arabic':
          responseNonIdCardFront['full_name']?.toString() ?? 'Not specified',
      'name_english': 'Not specified',
      'issue_date':
          responseNonIdCardBack['issueDate']?.toString() ?? 'Not specified',
      'expiry_date':
          responseNonIdCardBack['residencyExpirationDate']?.toString() ??
              'Not specified',
      'license_categories': responseIdEgyptDriverLicense['license_categories']
              is List
          ? responseIdEgyptDriverLicense['license_categories'].join(', ')
          : responseIdEgyptDriverLicense['license_categories']?.toString() ??
              'Not specified',
      'address':
          responseNonIdCardFront['address']?.toString() ?? 'Not specified',
      'card_id':
          responseNonIdCardFront['card_id']?.toString() ?? 'Not specified',
      'occupation':
          responseNonIdCardBack['workStatus']?.toString() ?? 'Not specified',
      'education': 'Not specified',
      'licenseIssueDate':
          responseNonIdCardBack['issueDate']?.toString() ?? 'Not specified',
      'religion':
          responseNonIdCardFront['country']?.toString() ?? 'Not specified',
      'status': 'yet',
      'birthdate':
          responseNonIdCardFront['birthdate']?.toString() ?? 'Not specified',
      'maritalStatus': added.toString(),
      'site': responseNonIdCardFront['address']?.toString() ?? 'Not specified',
      'employmentType':
          responseNonIdCardBack['residencyType']?.toString() ?? 'Not specified',
    };

    try {
      var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);

      var status1;
      try {
        status1 = jsonDecode(res);
      } catch (e) {
        throw FormatException("Invalid JSON response: $res");
      }

      isLoading = false;
      update();

      if (status1['status'] == 'success') {
        isDriverSaved = true;
        CRUD().post(
            link: '${AppLink.seferGizaServer}/auth/captin/register.php',
            payload: payload);
        CRUD().post(
            link: '${AppLink.seferAlexandriaServer}/auth/captin/register.php',
            payload: payload);
        mySnackbarSuccess('Foreign driver data saved successfully');
      } else {
        mySnackeBarError(
            '${'Failed to save driver data'.tr}: ${status1['message']}');
      }
    } catch (e) {
      isLoading = false;
      update();
      mySnackeBarError(
        'An error occurred while saving driver data'.tr,
      );
    }
  }

  Future<void> addDriverEgypt() async {
    isLoading = true;
    update();
    var added = await storage.read(key: 'name');
    String newPassword = generatePassword();
    print('Generated Password: $newPassword');
    var payload = {
      'first_name': responseIdEgyptDriverLicense['firstName']?.toString() ??
          'Not specified',
      'last_name': responseIdEgyptDriverLicense['lastName']?.toString() ??
          'Not specified',
      'email': email?.toString() ?? 'Not specified',
      'phone': phone?.toString() ?? 'Not specified',
      'id': driverId?.toString() ?? 'Not specified',
      'password': newPassword.toString() ?? '123456',
      'gender': responseIdEgyptBack['gender']?.toString() ?? 'Not specified',
      'license_type':
          responseIdEgyptDriverLicense['license_type']?.toString() ??
              'Not specified',
      'national_number':
          responseIdEgyptBack['nationalID']?.toString() ?? 'Not specified',
      'name_arabic': responseIdEgyptDriverLicense['name_arabic']?.toString() ??
          'Not specified',
      'name_english':
          responseIdEgyptDriverLicense['name_english']?.toString() ??
              'Not specified',
      'issue_date': responseIdEgyptDriverLicense['issue_date']?.toString() ??
          'Not specified',
      'expiry_date': responseIdEgyptDriverLicense['expiry_date']?.toString() ??
          'Not specified',
      'license_categories': responseIdEgyptDriverLicense['license_categories']
              is List
          ? responseIdEgyptDriverLicense['license_categories'].join(', ')
          : responseIdEgyptDriverLicense['license_categories']?.toString() ??
              'Not specified',
      'address': responseIdEgyptFront['address']?.toString() ?? 'Not specified',
      'card_id': responseIdEgyptFront['card_id']?.toString() ?? 'Not specified',
      'occupation':
          responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
      'education':
          responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
      'licenseIssueDate':
          responseIdEgyptDriverLicense['issue_date']?.toString() ??
              'Not specified',
      'religion':
          responseIdEgyptBack['religion']?.toString() ?? 'Not specified',
      'status': 'yet',
      'birthdate': extractDOB(
          responseIdEgyptDriverLicense['national_number'].toString()),
      'maritalStatus': added.toString(),
      'site': responseIdEgyptDriverLicense['address']?.toString() ??
          'Not specified',
      'employmentType':
          responseIdEgyptDriverLicense['employmentType']?.toString() ??
              'Not specified',
    };
    var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
    var status1 = jsonDecode(res);
    isLoading = false;
    update();
    // Handle response
    if (status1['status'] == 'success') {
      isDriverSaved = true;
      var res = CRUD().post(
          link: '${AppLink.seferGizaServer}/auth/captin/register.php',
          payload: payload);
      Log.print('res: ${res}');
      var res1 = CRUD().post(
          link: '${AppLink.seferAlexandriaServer}/auth/captin/register.php',
          payload: payload);
      Log.print('res: ${res1}');
      Get.snackbar('Success', 'Driver data saved successfully',
          backgroundColor: AppColor.greenColor);
      launchCommunication('whatsapp', phone.toString(),
          'you have seuccessfully registered in SEFER\n\n\n*Email* is *$email*\n\n*id* is *$driverId*\n\n*password* is *$newPassword*');
    } else {
      Get.snackbar('Error', 'Failed to save driver data',
          backgroundColor: Colors.red);
    }
  }

  Future<void> addDriverEgyptHanding() async {
    isLoading = true;
    update();
    String newPassword = generatePassword();
    var added = await storage.read(key: 'name');
    var payload = {
      'first_name': firstName.value.isNotEmpty
          ? firstName.value
          : responseIdEgyptDriverLicense['firstName'],
      'last_name': lastName.value.isNotEmpty
          ? lastName.value
          : responseIdEgyptDriverLicense['lastName'],
      'email': email?.toString() ?? 'Not specified',
      'phone': phone?.toString() ?? 'Not specified',
      'id': driverId?.toString() ?? 'Not specified',
      'password': newPassword.toString() ?? '123456',
      'gender': gender.value.isNotEmpty
          ? gender.value
          : responseIdEgyptBack['gender'],
      'license_type': licenseType.value.isNotEmpty
          ? licenseType.value
          : responseIdEgyptDriverLicense['license_type'],
      'national_number': nationalNumber.value.isNotEmpty
          ? nationalNumber.value
          : responseIdEgyptDriverLicense['national_number'],
      'name_arabic': nameArabic.value.isNotEmpty
          ? nameArabic.value
          : responseIdEgyptDriverLicense['name_arabic'],
      'name_english': nameEnglish.value.isNotEmpty
          ? nameEnglish.value
          : responseIdEgyptDriverLicense['name_english'],
      'issue_date': issueDate.value.isNotEmpty
          ? issueDate.value
          : responseIdEgyptDriverLicense['issue_date'],
      'expiry_date': expiryDate.value.isNotEmpty
          ? expiryDate.value
          : responseIdEgyptDriverLicense['expiry_date'],
      'license_categories': licenseCategories.value.isNotEmpty
          ? licenseCategories.value
          : responseIdEgyptDriverLicense['license_categories'] is List
              ? responseIdEgyptDriverLicense['license_categories'].join(', ')
              : responseIdEgyptDriverLicense['license_categories'],
      'address': address.value.isNotEmpty
          ? address.value
          : responseIdEgyptFront['address'],
      'card_id': cardId.value.isNotEmpty
          ? cardId.value
          : responseIdEgyptFront['card_id'],
      'occupation': occupation.value.isNotEmpty
          ? occupation.value
          : responseIdEgyptBack['occupation'],
      'education': education.value.isNotEmpty
          ? education.value
          : responseIdEgyptDriverLicense['issue_date'],
      'licenseIssueDate': licenseIssueDate.value.isNotEmpty
          ? licenseIssueDate.value
          : responseIdEgyptBack['religion'],
      'religion': religion.value.isNotEmpty ? religion.value : 'Not specified',
      'status': status.value.isNotEmpty ? status.value : 'yet',
      'birthdate':
          responseIdEgyptDriverLicense['national_number'].toString().length < 14
              ? extractDOB(responseIdEgyptBack['nationalID'])
              : extractDOB(
                  responseIdEgyptDriverLicense['national_number'].toString()),
      'maritalStatus': added.toString(),
      'fullNameMaritial': firstName.value.isNotEmpty
          ? firstName.value
          : responseIdEgyptDriverLicense['firstName'] +
              '_' +
              newPassword.toString(),
      'site': site.value.isNotEmpty
          ? site.value
          : responseIdEgyptDriverLicense['address'],
      'employmentType': employmentType.value.isNotEmpty
          ? employmentType.value
          : responseIdEgyptDriverLicense['employmentType'],
    };

    var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
    var status1 = jsonDecode(res);
    isLoading = false;
    update();

    // Handle response
    if (status1['status'] == 'success') {
      isDriverSaved = true;
      CRUD().post(
          link: '${AppLink.seferGizaServer}/auth/captin/register.php',
          payload: payload);
      CRUD().post(
          link: '${AppLink.seferAlexandriaServer}/auth/captin/register.php',
          payload: payload);
      Get.snackbar('Success', 'Driver data saved successfully',
          backgroundColor: AppColor.greenColor);
      launchCommunication('whatsapp', phone.toString(),
          'you have seuccessfully registered in SEFER\n\n\n*Email* is *$email*\n\n*id* is *$driverId*\n\n*password* is *$newPassword*');
    } else {
      Get.snackbar('Error', 'Failed to save driver data',
          backgroundColor: Colors.red);
    }
  }

  addCriminalDeocuments() async {
    var res = await CRUD().post(link: AppLink.addCriminalDocuments, payload: {
      "driverId": box.read(BoxName.driverID),
      "IssueDate": responseCriminalRecordEgypt['IssueDate'],
      "InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
    });
    if (res != 'failure') {
      Get.snackbar('uploaded sucssefuly'.tr, '');
      CRUD().post(
          link:
              '${AppLink.seferAlexandriaServer}/auth/captin/addCriminalDocuments.php',
          payload: {
            "driverId": box.read(BoxName.driverID),
            "IssueDate": responseCriminalRecordEgypt['IssueDate'],
            "InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
          });
      CRUD().post(
          link:
              '${AppLink.seferGizaServer}/auth/captin/addCriminalDocuments.php',
          payload: {
            "driverId": box.read(BoxName.driverID),
            "IssueDate": responseCriminalRecordEgypt['IssueDate'],
            "InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
          });
    }
  }

  var firstName = ''.obs;
  var lastName = ''.obs;
  var id = ''.obs;
  var password = '123456'.obs;
  var gender = ''.obs;
  var licenseType = ''.obs;
  var nationalNumber = ''.obs;
  var nameArabic = ''.obs;
  var nameEnglish = ''.obs;
  var issueDate = ''.obs;
  var expiryDate = ''.obs;
  var licenseCategories = ''.obs;
  var address = ''.obs;
  var cardId = ''.obs;
  var occupation = ''.obs;
  var education = ''.obs;
  var licenseIssueDate = ''.obs;
  var religion = ''.obs;
  var status = 'yet'.obs;
  var birthdate = ''.obs;
  var maritalStatus = ''.obs;
  var site = ''.obs;
  var employmentType = ''.obs;
  var vin = ''.obs;
  var carPlate = ''.obs;
  var make = ''.obs;
  var model = ''.obs;
  var year = ''.obs;
  var expirationDate = ''.obs;
  var color = ''.obs;
  var owner = ''.obs;
  var colorHex = ''.obs;
  var addressCar = ''.obs;
  var displacement = ''.obs;
  var fuel = ''.obs;
  var registrationDate = ''.obs;

  Future addRegistrationCarEgypt() async {
    try {
      final inspectionDate =
          responseIdCardDriverEgyptBack['inspection_date'].toString();
      final year = int.parse(inspectionDate.split('-')[0]);
      final inspectionDateTime = DateTime(year, 12, 31);
      isLoading = true;
      update();
      var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
        'driverID': driverId,
        'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
        'car_plate': responseIdCardDriverEgyptFront['car_plate'].toString(),
        'make': responseIdCardDriverEgyptBack['make'].toString(),
        'model': responseIdCardDriverEgyptBack['model'],
        'year': responseIdCardDriverEgyptBack['year'].toString(),
        'expiration_date':
            responseIdCardDriverEgyptFront['LicenseExpirationDate'].toString(),
        'color': responseIdCardDriverEgyptBack['color'],
        'owner': responseIdCardDriverEgyptFront['owner'],
        'color_hex': responseIdCardDriverEgyptBack['color_hex'].toString(),
        'address': responseIdCardDriverEgyptFront['address'].toString(),
        'displacement': responseIdCardDriverEgyptBack['engine'].toString(),
        'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
        'registration_date': '$inspectionDateTime',
      });
      isLoading = false;
      update();
      var status = jsonDecode(res);
      if (status['status'] == 'success') {
        isCarSaved = true;
        CRUD().post(
            link:
                '${AppLink.seferAlexandriaServer}/ride/RegisrationCar/add.php',
            payload: {
              'driverID': driverId,
              'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
              'car_plate':
                  responseIdCardDriverEgyptFront['car_plate'].toString(),
              'make': responseIdCardDriverEgyptBack['make'].toString(),
              'model': responseIdCardDriverEgyptBack['model'],
              'year': responseIdCardDriverEgyptBack['year'].toString(),
              'expiration_date':
                  responseIdCardDriverEgyptFront['LicenseExpirationDate']
                      .toString(),
              'color': responseIdCardDriverEgyptBack['color'],
              'owner': responseIdCardDriverEgyptFront['owner'],
              'color_hex':
                  responseIdCardDriverEgyptBack['color_hex'].toString(),
              'address': responseIdCardDriverEgyptFront['address'].toString(),
              'displacement':
                  responseIdCardDriverEgyptBack['engine'].toString(),
              'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
              'registration_date': '$inspectionDateTime',
            });
        CRUD().post(
            link: '${AppLink.seferGizaServer}/ride/RegisrationCar/add.php',
            payload: {
              'driverID': driverId,
              'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
              'car_plate':
                  responseIdCardDriverEgyptFront['car_plate'].toString(),
              'make': responseIdCardDriverEgyptBack['make'].toString(),
              'model': responseIdCardDriverEgyptBack['model'],
              'year': responseIdCardDriverEgyptBack['year'].toString(),
              'expiration_date':
                  responseIdCardDriverEgyptFront['LicenseExpirationDate']
                      .toString(),
              'color': responseIdCardDriverEgyptBack['color'],
              'owner': responseIdCardDriverEgyptFront['owner'],
              'color_hex':
                  responseIdCardDriverEgyptBack['color_hex'].toString(),
              'address': responseIdCardDriverEgyptFront['address'].toString(),
              'displacement':
                  responseIdCardDriverEgyptBack['engine'].toString(),
              'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
              'registration_date': '$inspectionDateTime',
            });

        Get.snackbar('Success', 'message',
            backgroundColor: AppColor.greenColor);
      }
    } catch (e) {}
  }

  Future<void> addRegistrationCarEgyptHandling() async {
    try {
      final inspectionDate =
          responseIdCardDriverEgyptBack['inspection_date']?.toString() ?? '';
      final year = inspectionDate.isNotEmpty
          ? int.parse(inspectionDate.split('-')[0])
          : DateTime.now().year;
      final inspectionDateTime = DateTime(year, 12, 31);
      Log.print('inspectionDateTime: $inspectionDateTime');

      isLoading = true;
      update();

      var payload = {
        'driverID': driverId,
        'vin': vin.value.isNotEmpty
            ? vin.value
            : responseIdCardDriverEgyptBack['chassis']?.toString() ?? '',
        'car_plate': carPlate.value.isNotEmpty
            ? carPlate.value
            : responseIdCardDriverEgyptFront['car_plate']?.toString() ?? '',
        'make': make.value.isNotEmpty
            ? make.value
            : responseIdCardDriverEgyptBack['make']?.toString() ?? '',
        'model': model.value.isNotEmpty
            ? model.value
            : responseIdCardDriverEgyptBack['model']?.toString() ?? '',
        'year': year.toString(),
        'expiration_date': expirationDate.value.isNotEmpty
            ? expirationDate.value
            : responseIdCardDriverEgyptFront['LicenseExpirationDate']
                    ?.toString() ??
                '',
        'color': color.value.isNotEmpty
            ? color.value
            : responseIdCardDriverEgyptFront['color']?.toString() ?? '',
        'owner': owner.value.isNotEmpty
            ? owner.value
            : responseIdCardDriverEgyptFront['owner']?.toString() ?? '',
        'color_hex': getColorHex(color.value),
        'address': addressCar.value.isNotEmpty
            ? addressCar.value
            : responseIdCardDriverEgyptFront['address']?.toString() ?? '',
        'displacement': displacement.value.isNotEmpty
            ? displacement.value
            : responseIdCardDriverEgyptBack['engine']?.toString() ?? '',
        'fuel': fuel.value.isNotEmpty
            ? fuel.value
            : responseIdCardDriverEgyptBack['fuel']?.toString() ?? '',
        'registration_date': inspectionDateTime.toIso8601String(),
      };

      Log.print('Payload: $payload');

      var res =
          await CRUD().post(link: AppLink.addRegisrationCar, payload: payload);

      isLoading = false;
      update();

      var status = jsonDecode(res);
      Log.print('res: $res');
      Log.print('status: $status');

      if (status['status'] == 'success') {
        isCarSaved = true;
        CRUD().post(
            link:
                '${AppLink.seferAlexandriaServer}/ride/RegisrationCar/add.php',
            payload: payload);

        CRUD().post(
            link: '${AppLink.seferGizaServer}/ride/RegisrationCar/add.php',
            payload: payload);
        Get.snackbar('Success', 'Registration successful',
            backgroundColor: AppColor.greenColor);
        Get.back();
      } else {
        Log.print('Error: Unexpected status: ${status['status']}');
        Get.snackbar('Error', 'Registration failed',
            backgroundColor: Colors.red);
      }
    } catch (e) {
      Log.print('Error: $e');
      Get.snackbar('Error', 'An error occurred during registration',
          backgroundColor: Colors.red);
    }
  }

  String getColorHex(String colorName) {
    Map<String, String> colorMap = {
      'white'.tr: '#FFFFFF',
      'maroon'.tr: '#800000', // Nabeeti
      'red'.tr: '#FF0000',
      'gray'.tr: '#808080',
      'green'.tr: '#008000',
      'navy blue'.tr: '#000080',
      'pink'.tr: '#FFC0CB',
      'black'.tr: '#000000',
      'dark blue'.tr: '#003366',
      'turquoise'.tr: '#40E0D0',
      'blue'.tr: '#0000FF',
      'red ochre'.tr: '#C72C48',
      'silver'.tr: '#C0C0C0',
      'mocha'.tr: '#3B2E2A',
      'tawny'.tr: '#D2B48C',
      'gold'.tr: '#FFD700',
      'verdi'.tr: '#008000',
      'orange'.tr: '#FFA500',
      'peach'.tr: '#FFDAB9',
      'brown'.tr: '#A52A2A',
      'raw gray'.tr: '#6C6E6E',
      'champagne'.tr: '#F7E7CE', // Champagne
      'bronze'.tr: '#CD7F32', // Bronze
      'red'.tr: '#FF0000', // Red
      'maroon'.tr: '#800000' // Maroon
    };

    return colorMap[colorName.toLowerCase()] ??
        '#000000'; // Default to black if color name is not found
  }

  Future getComplaintDataToAI() async {
    var res = await CRUD().get(
      link: AppLink.getComplaintAllDataForDriver,
      payload: {'driver_id': driverId.toString()},
    );
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      return d;
    } else {
      return [
        {'data': 'no data'}
      ];
    }
  }

  Future<dynamic> anthropicAIForComplaint() async {
    var dataComplaint = await getComplaintDataToAI();
    var messagesData = [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "$dataComplaint ${AppInformation.complaintPrompt} "
          }
        ]
      }
    ];
    var requestBody = jsonEncode({
      "model": "claude-3-haiku-20240307",
      "max_tokens": 1024,
      "temperature": 0,
      "system": "Json output only without any additional ",
      "messages": messagesData,
    });
    final response = await http.post(
      Uri.parse('https://api.anthropic.com/v1/messages'),
      headers: {
        'x-api-key': AK.anthropicAIkeySeferNew,
        'anthropic-version': '2023-06-01',
        'content-type': 'application/json'
      },
      body: requestBody,
    );
    if (response.statusCode == 200) {
      var responseData = jsonDecode(utf8.decode(response.bodyBytes));
      // Process the responseData as needed

      responseForComplaint = jsonDecode(responseData['content'][0]['text']);
    }
  }

  Future<dynamic> anthropicAI(
      String payload, String prompt, String idType) async {
    var messagesData = [
      {
        "role": "user",
        "content": [
          {"type": "text", "text": "$payload $prompt"}
        ]
      }
    ];

    var requestBody = jsonEncode({
      "model": "claude-3-haiku-20240307",
      "max_tokens": 1024,
      "temperature": 0,
      "system": "Json output only without any additional ",
      "messages": messagesData,
    });

    final response = await http.post(
      Uri.parse('https://api.anthropic.com/v1/messages'),
      headers: {
        'x-api-key': AK.anthropicAIkeySeferNewHamzaayedpython,
        'anthropic-version': '2023-06-01',
        'content-type': 'application/json'
      },
      body: requestBody,
    );
    Log.print('responseData: ${response.body}');
    if (response.statusCode == 200) {
      var responseData = jsonDecode(utf8.decode(response.bodyBytes));
      Log.print('responseData: ${responseData}');
      // Process the responseData as needed
      if (idType == 'car_back') {
        responseIdCardDriverEgyptBack =
            jsonDecode(responseData['content'][0]['text']);
      } else if (idType == 'car_front') {
        responseIdCardDriverEgyptFront =
            jsonDecode(responseData['content'][0]['text']);
      } else if (idType == 'id_front') {
        responseIdEgyptFront = jsonDecode(responseData['content'][0]['text']);
      } else if (idType == 'id_back') {
        responseIdEgyptBack = jsonDecode(responseData['content'][0]['text']);
      } else if (idType == 'driver_license') {
        responseIdEgyptDriverLicense =
            jsonDecode(responseData['content'][0]['text']);
      } else if (idType == 'criminalRecord') {
        responseCriminalRecordEgypt =
            jsonDecode(responseData['content'][0]['text']);
      }

      update();
      return responseData.toString();
    }
    return responseIdCardDriverEgyptBack.toString();
  }

  Future<void> geminiAiExtraction(String prompt, payload, String idType) async {
    var requestBody = jsonEncode({
      "contents": [
        {
          "parts": [
            {"text": "$payload $prompt"}
          ]
        }
      ],
      "generationConfig": {
        "temperature": 1,
        "topK": 64,
        "topP": 0.95,
        "maxOutputTokens": 8192,
        "stopSequences": []
      },
      "safetySettings": [
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        }
      ]
    });

    final response = await http.post(
      Uri.parse(''),
      // 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
      // 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${AK.geminiApi}'),
      // 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
      headers: {'Content-Type': 'application/json'},
      body: requestBody,
    );

    if (response.statusCode == 200) {
      var responseData = jsonDecode(response.body);
      // Process the responseData as needed

      var result = responseData['candidates'][0]['content']['parts'][0]['text'];
      RegExp regex = RegExp(r"```json([^`]*)```");
      String? jsonString =
          regex.firstMatch(responseData.toString())?.group(1)?.trim();

      if (jsonString != null) {
        // Convert the JSON object to a String
        jsonString = jsonEncode(json.decode(jsonString));

        if (idType == 'car_back') {
          responseIdCardDriverEgyptBack = jsonDecode(jsonString);
        } else if (idType == 'car_front') {
          responseIdCardDriverEgyptFront = jsonDecode(jsonString);
        } else if (idType == 'id_front') {
          responseIdEgyptFront = jsonDecode(jsonString);
        } else if (idType == 'id_back') {
          responseIdEgyptBack = jsonDecode(jsonString);
        } else if (idType == 'driver_license') {
          responseIdEgyptDriverLicense = jsonDecode(jsonString);
        }

        update();
      } else {
        Get.snackbar('Error', "JSON string not found",
            backgroundColor: AppColor.redColor);
      }

      // Rest of your code...
    } else {}
  }
}
