import 'dart:convert';

import 'package:dropdown_search/dropdown_search.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:nhance_partner/presentation/screens/Enquiry/enquiry/policy_popup.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../core/config/env.dart';
import '../../../../core/routing/routes.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../../data/utils/toastNotification.dart';
import '../../../../data/utils/validators.dart';
import '../../../layouts/main_layout.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';
import '../../../providers/quotation_staff_proivder.dart';
import '../../../providers/userRoleProvider.dart';
import '../../../themes/indicators/custom_loader.dart';
import '../../../themes/indicators/customizd_file_upload.dart';
import '../../../themes/indicators/date_field_theme.dart';
import '../../../themes/indicators/export_btn.dart';
import '../../../themes/indicators/input_field_decoration.dart';
import '../../../themes/indicators/search_field_theme.dart';
import '../../../themes/indicators/text_field_theme.dart';
import '../../../widgets/custom_action_popup.dart';
import '../../Enquiry/policy_claims_endros/sub_claims.dart';
import '../../Enquiry/policy_claims_endros/sub_endrosment.dart';

class PolicyStaffEnqList extends ConsumerStatefulWidget {
  // final List<Map<String, dynamic>>? data;
  // dynamic id;
  // PolicyStaffEnqList({super.key, this.data, this.id});
  PolicyStaffEnqList({super.key});
  @override
  ConsumerState<PolicyStaffEnqList> createState() => PolicyStaffEnqListState();
}

class PolicyStaffEnqListState extends ConsumerState<PolicyStaffEnqList> {
  int currentPage = 0;
  int itemsPerPage = 10;

  List<Map<String, dynamic>> dataVal = [];

  final TextEditingController _searchController = TextEditingController();

  late ApiService apiService;
  final _formKey = GlobalKey<FormState>();
  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKey =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKeyBroker =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKeyAgent =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>>
  dropDownKeyInsurerEnqAsgn =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  List<Map<String, dynamic>> getBrokerData = [];
  List<Map<String, dynamic>> filteredBrokerData = [];
  String? selectedBroker;
  String? selectedBrokerName;
  String? selectedAgent;
  String? selectedInsurer;

  List<Map<String, dynamic>> getAgentListData = [];
  List<Map<String, dynamic>> filteredAgentData = [];

  List<String> tabHeader = [
    'name',
    'email',
    'mobile',
    'code',
    'address',
    'regNo',

    'insurer',
    'regNum',
    'idv',
    'premium_amount',
    'planType',
    'policyInsName',
    'policyPremiumAmount',
    'policyIdv',
    'policyNumber',
    'policyPaymentMode',
    'issueDate',
    'startDate',
    'endDate',

    'tp',
    'od',
    'pa',
    'cgst',
    'sgst',
    'igst',
    'rto_state_code',
    'rto_city_code',
    'weight',
    'fuel_type',
    'date_of_registration',
    'year_of_manufacture',
    'engine_no',
    'chassis_no',
    'make',
    'model',
    'cubic_capacity',
    'vehicle_type',
    'premiumTOT',
    'commison_amount',
    'commison_applied_rule',
  ];
  late String isActive = "1";
  PlatformFile? docUploadedFile;
  PlatformFile? docPDFUploadedFile;

  // PlatformFile? passportFile;
  String? selectedFileNames;
  String? selectedPDFFileNames;
  String? passportFileUrlFromApi;
  String? docUploadedFileUrlFromApi;
  String? docUploadedPDFFileUrlFromApi;

  String? selectedId;
  bool isLoading = false;
  bool isquotation = false;
  bool hasPolicyData = false;

  Map<String, TextEditingController> controllers = {};
  String? _token;
  dynamic userId;
  dynamic managerId;
  dynamic enqQuotation;
  dynamic selectedEnquiryId;
  dynamic acceptedQuotationId;
  dynamic choosedPolcyId;

  dynamic roleId;
  dynamic enqBrokerName;
  dynamic selectedPaymentMode;

  List<Map<String, dynamic>> getVehicleTypeData = [];
  List<Map<String, dynamic>> filteredVechicleData = [];

  List<Map<String, dynamic>> getInsurersData = [];
  List<Map<String, dynamic>> filteredInsurersData = [];

  late Map<String, dynamic> enquiryData;
  late Map<String, dynamic> policyData;
  Map<String, dynamic>? quotationAcceptedData;

  Map<String, dynamic> dataDetails() {
    final data = {
      "quotation_id": acceptedQuotationId,
      "insured_name": controllers["policyInsName"]?.text,
      "issued_date": controllers["issueDate"]?.text,
      "start_date": controllers["startDate"]?.text,
      "end_date": controllers["endDate"]?.text,
      // "premium_amount": controllers["premium_amount"]?.text,
      // "premium_amount": controllers["policyPremiumAmount"]?.text,
      "policy_number": controllers["policyNumber"]?.text,
      "payment_mode": controllers["policyPaymentMode"]?.text,
      "broker_id": selectedBroker,
      "tp": controllers["tp"]?.text,
      "od": controllers["od"]?.text,
      "pa": controllers["pa"]?.text,
      "cgst": controllers["cgst"]?.text,
      "sgst": controllers["sgst"]?.text,
      "igst": controllers["igst"]?.text,
      "premium_amount": controllers["premiumTOT"]?.text,
      "manager_id": managerId,
      // "policy_pdf_file_name": "policy_doc.pdf",
      // "policy_payment_receipt_file_name": "receipt_doc.pdf",
      // "created_by": userId,
    };
    return data;
  }

  Map<String, dynamic> dataForPolicyPDFDetails() {
    final data = {"quotation_id": acceptedQuotationId, "manager_id": managerId};
    return data;
  }

  List<Map<String, dynamic>> quotationData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];
  bool isLoader = false;

  @override
  void initState() {
    super.initState();
    apiService = ApiService();

    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }

    // Add listeners to text fields
    controllers["tp"]?.addListener(calculateAmount);
    controllers["od"]?.addListener(calculateAmount);
    controllers["pa"]?.addListener(calculateAmount);
    controllers["cgst"]?.addListener(calculateAmount);
    controllers["sgst"]?.addListener(calculateAmount);
    controllers["igst"]?.addListener(calculateAmount);

    // updateData();
    _initializeToken();
    // Future.microtask(() {
    //   managerId = ref.watch(managerIdProvider);
    //   userId = ref.watch(userIdProvider);
    //
    //   getQuotationList(managerId);
    // });

    if (kIsWeb) {
      Future.microtask(() => _restoreManagerId(ref));
    }

    Future.microtask(() {
      managerId = ref.read(managerIdProvider); // ✅ use read
      userId = ref.read(userIdProvider); // ✅ use read
      roleId = ref.read(userRoleProvider); // ✅ use read
      enqBrokerName = ref.read(enqBrokerNameProvider);

      print('QmanagerId - $managerId');
      print('QuserId - $userId');
      enqQuotation = ref.read(quotationStaffIdProvider); // ✅ use read
      print('QenqQuotation - $enqQuotation');

      controllers["cgst"]?.text = '0';
      controllers["sgst"]?.text = '0';
      controllers["igst"]?.text = '0';
      getBroker();
      getInsurers();
      if (enqQuotation != null) {
        _loadData(enqQuotation);
      }

      if (managerId != null) {
        print('managerId - $managerId');
        getAgentList(managerId);
      }
    });
  }

  Future<void> _restoreManagerId(WidgetRef ref) async {
    final prefs = await SharedPreferences.getInstance();

    final String? savedId = prefs.getString('enqStaffDataId');
    final String? savedBrokerName = prefs.getString(
      'enqBrokerName',
    ); // already a string

    if (savedBrokerName != null) {
      ref.read(enqBrokerNameProvider.notifier).state = savedBrokerName;
    }

    if (savedId != null) {
      ref.read(quotationStaffIdProvider.notifier).state = savedId;
      print("savedenqStaffDataId ID restored: $savedId");

      _loadData(savedId);
    }
  }

  void calculateAmount() {
    print('calculateAmount 1');
    setState(() {
      double tp = double.tryParse(controllers["tp"]?.text ?? '0') ?? 0;
      double od = double.tryParse(controllers["od"]?.text ?? '0') ?? 0;
      double pa = double.tryParse(controllers["pa"]?.text ?? '0') ?? 0;
      double cgst = double.tryParse(controllers["cgst"]?.text ?? '0') ?? 0;
      double sgst = double.tryParse(controllers["sgst"]?.text ?? '0') ?? 0;
      double igst = double.tryParse(controllers["igst"]?.text ?? '0') ?? 0;

      double total = tp + od + pa + cgst + sgst + igst;

      print('Val : $total');
      controllers["premiumTOT"]!.text = total.toStringAsFixed(2);
    });
  }

  @override
  void dispose() {
    // Dispose all TextEditingControllers
    for (var controller in controllers.values) {
      controller.dispose();
    }
    super.dispose();
  }

  Future<void> _initializeToken() async {
    _token = await AuthService.getToken();
    print("APISERTOKEN - $_token");
  }

  Future<void> _loadData(enqQuotation) async {
    getQuotationList(enqQuotation);
  }

  Future<void> getQuotationList(enqQuotation) async {
    print('getClaimList called enqQuotation- $enqQuotation');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.findEnqQuotePolicyView(enqQuotation);

      if (response['status'] == 'success') {
        print('quoationListData - ${response['data']}');
        final data = response['data'];
        setState(() {
          enquiryData = Map<String, dynamic>.from(data['enquiry']);
          print('ra-1');
          quotationData = List<Map<String, dynamic>>.from(data['quotations']);
          print('ra-2');
          policyData = Map<String, dynamic>.from(data['policies']);
          print('ra-3');
          // enquiryData = Map<String, dynamic>.from(response['data']['enquiry']);
          // print('enquiryData - ${enquiryData}');
          updatePolicyData(policyData);
          updateEnquiryData(enquiryData);
          // quotationData = List<Map<String, dynamic>>.from(response['data']);
          // quotationData = List<Map<String, dynamic>>.from(
          //   response['data']['quotations'],
          // );
          print('quotationData - ${quotationData}');
          updateQuotationData(quotationData);

          // policyData = Map<String, dynamic>.from(response['data']['policies']);

          print('policyData - ${policyData}');

          originalData = quotationData;
          filteredData = List.from(originalData);
          // print('originalData - $getClaimPolicies');
        });
      } else {
        quotationData = [];
        originalData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getAgentList(id) async {
    print('getAgentListData called');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchAgentNameDropDown(id);
      print('getAgentListData called response');
      print('get Agent- ${response['data']}');
      if (response['status'] == 'success') {
        print('get Agent- ${response['data']}');
        setState(() {
          getAgentListData = List<Map<String, dynamic>>.from(response['data']);
          print('API Data - $getAgentListData');

          filteredAgentData = List.from(getAgentListData);
          print('originalAgentData - $filteredAgentData');
        });
      } else {
        getAgentListData = [];
        filteredAgentData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getInsurers() async {
    print('Insurers called');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchMasterDropDown('Insurers');

      if (response['status'] == 200) {
        print('getInsurers - ${response['data']}');
        setState(() {
          getInsurersData = List<Map<String, dynamic>>.from(response['data']);
          print('API Data - $getInsurersData');

          filteredInsurersData = List.from(getInsurersData);
          print('originalData - $filteredInsurersData');
        });
      } else {
        getInsurersData = [];
        filteredInsurersData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getBroker() async {
    print('getBroker called');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchMasterDropDown('Broker');

      if (response['status'] == 200) {
        print('getBroker - ${response['data']}');
        setState(() {
          getBrokerData = List<Map<String, dynamic>>.from(response['data']);
          print('API Data - $getBrokerData');

          filteredBrokerData = List.from(getBrokerData);
          print('originalData - $filteredBrokerData');
        });
      } else {
        getBrokerData = [];
        filteredBrokerData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void updateEnquiryData(enquiryData) {
    setState(() {
      selectedEnquiryId = enquiryData['id'];
      print('selectedEnquiryId- $selectedEnquiryId');
      controllers["regNum"]?.text = enquiryData['reg_no'];
      controllers["insurer"]?.text = enquiryData['insurer_name'];
      controllers["policyInsName"]?.text = enquiryData['name'];
    });
  }

  void updateQuotationData(List<Map<String, dynamic>> quotationData) {
    try {
      final acceptedItem = quotationData.firstWhere(
        (item) => item['status'] == 'Accepted',
      );

      quotationAcceptedData = acceptedItem;
      print('AcceptedData YYY - $quotationAcceptedData');

      if (quotationAcceptedData != null) {
        if (!mounted) return;
        print('AcceptedData YYY2');
        setState(() {
          controllers["insurer"]?.text = quotationAcceptedData?['insurer_name'];
          acceptedQuotationId = quotationAcceptedData?['id']?.toString() ?? '';

          controllers["idv"]?.text =
              quotationAcceptedData?['insured_declared_value']?.toString() ??
              '';
          // controllers["premium_amount"]?.text =
          //     quotationAcceptedData?['premium_amount']?.toString() ?? '';
          controllers["planType"]?.text =
              quotationAcceptedData?['insurance_plan_type']?.toString() ?? '';
          controllers["policyPaymentMode"]?.text =
              quotationAcceptedData?['payment_mode_value']?.toString() ?? '';
          selectedBroker = quotationAcceptedData?['broker_id'] ?? '';
          selectedBrokerName = quotationAcceptedData?['broker_name'] ?? '';
        });
      }
    } catch (e) {
      quotationAcceptedData = null;
      print('No Accepted quotation found');
    }
  }

  String fixInvalidDate(dynamic value) {
    if (value == null) return '';
    final str = value.toString();

    // Check for your invalid date patterns
    if (str.contains('--0001') || str == '30-11--0001' || str == '0000-00-00') {
      return '';
    }
    return str;
  }

  void updatePolicyData(Map<String, dynamic> policyData) {
    print("updatePolicyDataupdatePolicyData - $policyData");

    if (!mounted || policyData.isEmpty) return;

    setState(() {
      hasPolicyData = true;
      selectedAgent = policyData['agent_id']?.toString() ?? '';
      selectedPaymentMode = policyData['payment_mode_id']?.toString() ?? '';
      acceptedQuotationId = policyData['quotation_id']?.toString() ?? '';
      choosedPolcyId = policyData['id']?.toString() ?? '';
      controllers["policyInsName"]?.text =
          policyData['insured_name']?.toString() ?? '';
      controllers["idv"]?.text =
          policyData['insured_declared_value']?.toString() ?? '';
      controllers["policyPremiumAmount"]?.text =
          policyData['premium_amount']?.toString() ?? '';
      controllers["planType"]?.text =
          policyData['insurance_plan_type']?.toString() ?? '';
      controllers["policyNumber"]?.text =
          policyData['policy_number']?.toString() ?? '';
      controllers["policyPaymentMode"]?.text =
          policyData['payment_mode']?.toString() ?? '';
      selectedPaymentMode = policyData['payment_mode_value']?.toString() ?? '';
      controllers["issueDate"]?.text = fixInvalidDate(
        policyData['issued_date'],
      );
      controllers["startDate"]?.text = fixInvalidDate(policyData['start_date']);
      controllers["endDate"]?.text = fixInvalidDate(policyData['end_date']);

      // controllers["issueDate"]?.text =
      //     policyData['issued_date']?.toString() ?? '';
      // controllers["startDate"]?.text =
      //     policyData['start_date']?.toString() ?? '';
      // controllers["endDate"]?.text = policyData['end_date']?.toString() ?? '';

      controllers["tp"]?.text = policyData['tp']?.toString() ?? '';
      controllers["od"]?.text = policyData['od']?.toString() ?? '';
      controllers["pa"]?.text = policyData['pa']?.toString() ?? '';

      controllers["cgst"]?.text = policyData['cgst']?.toString() ?? '';
      controllers["sgst"]?.text = policyData['sgst']?.toString() ?? '';
      controllers["igst"]?.text = policyData['igst']?.toString() ?? '';
      controllers["premiumTOT"]?.text =
          policyData['premium_amount']?.toString() ?? '';

      controllers["make"]?.text = policyData['make']?.toString() ?? '';
      controllers["model"]?.text = policyData['model']?.toString() ?? '';
      controllers["vehicle_type"]?.text =
          policyData['vehicle_type']?.toString() ?? '';
      controllers["fuel_type"]?.text =
          policyData['fuel_type']?.toString() ?? '';
      controllers["engine_no"]?.text =
          policyData['engine_no']?.toString() ?? '';
      controllers["chassis_no"]?.text =
          policyData['chassis_no']?.toString() ?? '';
      controllers["cubic_capacity"]?.text =
          policyData['cubic_capacity']?.toString() ?? '';
      controllers["weight"]?.text = policyData['weight']?.toString() ?? '';
      controllers["year_of_manufacture"]?.text =
          policyData['year_of_manufacture']?.toString() ?? '';
      controllers["date_of_registration"]?.text = fixInvalidDate(
        policyData['date_of_registration'],
      );
      controllers["rto_state_code"]?.text = fixInvalidDate(
        policyData['rto_state_code'],
      );
      controllers["rto_city_code"]?.text = fixInvalidDate(
        policyData['rto_city_code'],
      );
      controllers["commission_amount"]?.text = fixInvalidDate(
        policyData['commission_amount'],
      );
      controllers["commission_applied_rule"]?.text = fixInvalidDate(
        policyData['commission_applied_rule'],
      );

      selectedBroker = policyData['broker_id'] ?? '';
      selectedBrokerName = policyData['broker_name'] ?? '';
      // RC FILE
      String? rcPath = policyData["policy_pdf_file_name"];
      if (rcPath != null && rcPath.isNotEmpty) {
        selectedPDFFileNames = rcPath.split('/').last; // UI filename
        docUploadedPDFFileUrlFromApi = rcPath; // API download URL
        docPDFUploadedFile = null;
        // docUploadedRCFile =
        //     rcFileUrlFromApi as PlatformFile?; // user has not re-uploaded yet
      } else {
        selectedPDFFileNames = null; // no UI file shown
        docUploadedPDFFileUrlFromApi = null;
        docPDFUploadedFile = null;
      }

      // ID PROOF FILE
      String? idProofPath = policyData["policy_payment_receipt_file_name"];
      if (idProofPath != null && idProofPath.isNotEmpty) {
        selectedFileNames = idProofPath.split('/').last;
        docUploadedFileUrlFromApi = idProofPath; // ✅ FIXED → correct variable
        docUploadedFile = null;
        // docUploadedIDProof = idProofFileUrlFromApi as PlatformFile?;
      } else {
        selectedFileNames = null;
        docUploadedFileUrlFromApi = null;
        docUploadedFile = null;
      }
    });
  }

  String _formatDate(String rawDate) {
    try {
      final dateTime = DateTime.parse(rawDate);
      return DateFormat('dd-MM-yyyy').format(dateTime); // 24-hour format
    } catch (e) {
      return rawDate; // fallback if parsing fails
    }
  }

  void updateUploadPDFPolicyData(Map<String, dynamic> policyData) {
    print('updateUploadPDFPolicyDataJJ - $policyData');
    if (!mounted || policyData.isEmpty) return;

    setState(() {
      hasPolicyData = true;
      choosedPolcyId = policyData['id']?.toString() ?? '';

      controllers["policyNumber"]?.text =
          policyData['policy_number']?.toString() ?? '';
      controllers["policyPaymentMode"]?.text =
          policyData['payment_mode_value']?.toString() ?? '';
      selectedPaymentMode = policyData['payment_mode_value']?.toString() ?? '';

      controllers["issueDate"]?.text =
          _formatDate(policyData['issued_date']!.toString()) ?? '';
      controllers["startDate"]?.text =
          _formatDate(policyData['start_date']!.toString()) ?? '';
      controllers["endDate"]?.text =
          _formatDate(policyData['end_date']!.toString()) ?? '';

      final premium = policyData['premium'];
      if (premium != null) {
        final taxes = premium['taxes'] ?? {};
        controllers["tp"]?.text = premium["tp"]?.toString() ?? '0';
        controllers["od"]?.text = premium["od"]?.toString() ?? '0';
        controllers["pa"]?.text = premium["pa"]?.toString() ?? '0';
        controllers["cgst"]?.text = taxes["cgst"]?.toString() ?? '0';
        controllers["sgst"]?.text = taxes["sgst"]?.toString() ?? '0';
        controllers["igst"]?.text = taxes["igst"]?.toString() ?? '0';
        controllers["premiumTOT"]?.text = premium["total"]?.toString() ?? '0';
      }

      // RC FILE
      String? rcPath = policyData["policy_pdf_file_name"];
      if (rcPath != null && rcPath.isNotEmpty) {
        selectedPDFFileNames = rcPath.split('/').last; // UI filename
        docUploadedPDFFileUrlFromApi = rcPath; // API download URL
        docPDFUploadedFile = null;
        // docUploadedRCFile =
        //     rcFileUrlFromApi as PlatformFile?; // user has not re-uploaded yet
      } else {
        selectedPDFFileNames = null; // no UI file shown
        docUploadedPDFFileUrlFromApi = null;
        docPDFUploadedFile = null;
      }
    });
  }

  void handleSave() {
    // if (!_formKey.currentState!.validate()) return;
    setState(() {
      // if (_formKey.currentState!.validate()) {
      calculateAmount();
      dataDetails();
      final dataSet = dataDetails();
      print("dataSetPolicy - $dataSet");

      final bool isUpdating = choosedPolcyId != null;

      // if (!isUpdating && selectedBrokerName == 'Nhance') {
      //   // if (!isUpdating && enqBrokerName == 'Nhance') {
      //   ToastHelper.showErrorToast(context, "Policy PDF is required");
      //   return;
      // }
      // (enqBrokerName != 'Nhance')
      // File validations
      if (
      // (selectedBrokerName != 'Nhance') &&
      (docPDFUploadedFile == null || docPDFUploadedFile?.bytes == null) &&
          (docUploadedPDFFileUrlFromApi == null ||
              docUploadedPDFFileUrlFromApi!.isEmpty)) {
        ToastHelper.showErrorToast(context, "Policy PDF is required");
        return;
      }
      createUserData(dataSet);
      // } else {
      //   // isDi sable = false;
      // }
    });
  }

  void handleUploadPolicy() {
    setState(() {
      dataForPolicyPDFDetails();
      final dataSet = dataForPolicyPDFDetails();
      print("dataSetPolicy - $dataSet");
      // File validations
      if ((docPDFUploadedFile == null || docPDFUploadedFile?.bytes == null) &&
          (docUploadedPDFFileUrlFromApi == null ||
              docUploadedPDFFileUrlFromApi!.isEmpty)) {
        ToastHelper.showErrorToast(context, "Policy PDF is required");
        return;
      }
      createPolicyPDFData(dataSet);
    });
  }

  Future<void> attachFiles(http.MultipartRequest request) async {
    Future<void> addFileOrKeepName(
      PlatformFile? file,
      String? apiFileName,
      String fieldName,
    ) async {
      if (file != null) {
        // User uploaded a new file → send as multipart
        if (file.bytes != null) {
          request.files.add(
            http.MultipartFile.fromBytes(
              fieldName,
              file.bytes!,
              filename: file.name,
            ),
          );
        } else if (file.path != null) {
          request.files.add(
            await http.MultipartFile.fromPath(
              fieldName,
              file.path!,
              filename: file.name,
            ),
          );
        }
        print("📎 Attached new file → $fieldName");
      } else if (apiFileName != null && apiFileName.isNotEmpty) {
        // No new upload → tell backend to keep old file
        request.fields[fieldName] = apiFileName;
        print("🔗 Kept old file → $fieldName = $apiFileName");
      } else {
        // Nothing at all
        request.fields[fieldName] = "";
      }
    }

    await addFileOrKeepName(
      docPDFUploadedFile,
      docUploadedPDFFileUrlFromApi,
      'policy_pdf_file_name',
    );
    // await addFileOrKeepName(
    //   docUploadedFile,
    //   docUploadedFileUrlFromApi,
    //   'policy_payment_receipt_file_name',
    // );
  }

  Future<void> createUserData(Map<String, dynamic> userData) async {
    final bool isUpdating = choosedPolcyId != null;
    final id = choosedPolcyId;
    // final id = '1';
    // print('UPDId- $id');

    // final bool isUpdating = false;
    final uri = Uri.parse(
      isUpdating
          ? '${Env.apiUrl}policy/updatePolicy'
          : '${Env.apiUrl}policy/createPolicy',
    );
    if (_token == null) {
      throw Exception('Token not found. Please log in.');
    }

    // Use MultipartRequest (POST only)
    final request = http.MultipartRequest('POST', uri);
    request.headers['Authorization'] = 'Bearer $_token';
    request.headers['app-signature'] = Env.App_Signature;

    // If updating, spoof the method Laravel-style
    if (isUpdating) {
      request.fields['id'] = id!;
      request.fields['updated_by'] = userId!.toString();
    } else {
      request.fields['created_by'] = userId!.toString();
    }

    print("USerDAta - $userData");

    // userData.forEach((key, value) {
    //   request.fields[key] = value.toString();
    //   print("✅ Encoded travel_details2: ${request.fields[key]}");
    // });
    await attachFiles(request);
    userData.forEach((key, value) {
      if (key != 'policy_pdf_file_name'
      // &&
      // key != 'policy_payment_receipt_file_name'
      ) {
        request.fields[key] = value.toString();
        print("✅ Encoded $key: ${request.fields[key]}");
      } else {
        print('Something Missing..');
      }
    });

    // attach files

    // request.fields['agent_id'] = selectedId.toString();

    print(" Sending request with fields: ${request.fields}");

    try {
      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");

      if (response.statusCode == 200 || response.statusCode == 201) {
        // dispose();
        print("✅ Agent submitted successfully!");
        ToastHelper.showSuccessToast(context, 'Saved Policy');
        print("Response: ${response.body}");

        Navigator.pop(context);
        if (isUpdating) {
          ref.read(enquiryIdProvider.notifier).state = null;
          context.go(AppRoutes.enquiryForStaff);
        } else {
          ref.read(enquiryIdProvider.notifier).state = null;
          context.go(AppRoutes.enquiryForStaff);
        }
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        print("❌ Submission failed. Status: ${response.statusCode}");
        print("Body: ${response.body}");

        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Policy Creation Failed"),
              content: Text(
                "There was a problem in creating policy. Please try again.",
              ),
              actions: [
                TextButton(
                  child: Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      print("🔥 Error submitting user: $e");
    }
  }

  Future<void> createPolicyPDFData(Map<String, dynamic> userData) async {
    final bool isUpdating = choosedPolcyId != null;
    final id = choosedPolcyId;
    // final id = '1';
    // print('UPDId- $id');

    final uri = Uri.parse('${Env.apiUrl}policy/uploadPolicyFile');
    if (_token == null) {
      throw Exception('Token not found. Please log in.');
    }

    // Use MultipartRequest (POST only)
    final request = http.MultipartRequest('POST', uri);
    request.headers['Authorization'] = 'Bearer $_token';
    request.headers['app-signature'] = Env.App_Signature;

    // If updating, spoof the method Laravel-style
    if (isUpdating) {
      request.fields['id'] = id!;
      request.fields['updated_by'] = userId!.toString();
    } else {
      request.fields['created_by'] = userId!.toString();
    }

    print("USerDAta - $userData");

    await attachFiles(request);
    userData.forEach((key, value) {
      if (key != 'policy_pdf_file_name') {
        request.fields[key] = value.toString();
        print("✅ Encoded $key: ${request.fields[key]}");
      } else {
        print('Something Missing..');
      }
    });

    print(" Sending request with fields: ${request.fields}");

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const CustomLoader(
        message: 'Loading data...',
        loaderColor: Colors.deepPurple,
        useBlurBackground: true,
      ),
    );

    try {
      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");

      if (response.statusCode == 200 || response.statusCode == 201) {
        // Close the loader before showing any message
        Navigator.of(context, rootNavigator: true).pop();
        // dispose();
        print("✅ PDF submitted successfully!");
        ToastHelper.showSuccessToast(context, 'PDF Uploaded');
        print("Response: ${response.body}");

        final Map<String, dynamic> jsonResponse = jsonDecode(response.body);
        final policy =
            jsonResponse['data']?['file_read_data']?['value']?['policy'];
        if (policy != null) {
          final extractedData = {
            'id': jsonResponse['data']?['policy_id']?.toString(),
            'policy_number': policy['policy_number'],
            'issued_date': policy['issue_date'],
            'start_date': policy['period']?['start'],
            'end_date': policy['period']?['end'],
            'payment_mode': policy['payment_mode'] ?? 'online',
            // optional if available
            'policy_pdf_file_name':
                jsonResponse['data']?['policy_pdf_file_name'],

            // ✅ include premium details here
            'premium':
                jsonResponse['data']?['file_read_data']?['value']?['premium'],
            // optional if your API returns it
          };

          print('extractedData - $extractedData');
          updateUploadPDFPolicyData(extractedData);
        }
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        print("❌ Submission failed. Status: ${response.statusCode}");
        print("Body: ${response.body}");

        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(" Upload Policy Failed"),
              content: Text(
                "There was a problem in uploading pdf. Please try again.",
              ),
              actions: [
                TextButton(
                  child: Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      print("🔥 Error submitting user: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return SelectionArea(
        child: AlertDialog(
      backgroundColor: Color(0xfff8fafc),
      contentPadding: const EdgeInsets.fromLTRB(24.0, 2.0, 24.0, 24.0),
      titlePadding: const EdgeInsets.fromLTRB(24.0, 4.0, 24.0, 2.0),
      title: Container(
        // color: Colors.blue,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,

          children: [
            Text(
              'Policy',
              style: GoogleFonts.poppins(
                fontSize: 14,
                // color: Color(0xFF2E7D6E),
                fontWeight: FontWeight.w600,
              ),
            ),
            IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(Icons.close, size: 18),
            ),
          ],
        ),
      ),
      content: Container(
        // color: Colors.amber,
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            children: [
              // Expanded(
              //   child:
              // Container(
              //   // color: Colors.white,
              //   padding: EdgeInsets.all(16.0),
              //   child: SingleChildScrollView(
              //     scrollDirection: Axis.vertical,
              //     child: Column(
              //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //       children: [buildFormFields(context)],
              //     ),
              //   ),
              // ),
              buildFormFields(context),
              SizedBox(height: 1),
            ],
          ),
        ),
        // ),
      ),
    ));
  }

  Widget buildDocRC(BuildContext context, bool isMobile) {
    return GestureDetector(
      onTap: () {
        // print("Upload $idget.id}{w");
        final selectedId = selectedEnquiryId;
        // final path =
        //     'agent/downloadAgentIncentiveFile?id=$selectedId';
        final path =
            'enquiry/downloadEnquiryFile?enquiry_id=$selectedId&file_type=rc';
        apiService.getPdfDownload(path, selectedId);
      },
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: const Color(0xFF425B5B),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              "Download RC",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w200,
                color: Colors.white,
              ),
            ),
            ?isMobile ? null : SizedBox(width: 15),
            // isMobile ? const Spacer() : const SizedBox(width: 15),
            const Icon(
              Icons.file_download_outlined,
              size: 16,
              color: Colors.white,
            ),
          ],
        ),
      ),
    );
  }

  Widget buildDocIdProof(BuildContext context, bool isMobile) {
    return GestureDetector(
      onTap: () {
        print("Upload $selectedEnquiryId");
        final selectedId = selectedEnquiryId;
        // final path =
        //     'agent/downloadAgentIncentiveFile?id=$selectedId';
        final path =
            'enquiry/downloadEnquiryFile?enquiry_id=$selectedId&file_type=id_proof';
        apiService.getPdfDownload(path, selectedId);
      },
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: const Color(0xFF425B5B),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "Download ID Proof",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w200,
                color: Colors.white,
              ),
            ),
            ?isMobile ? null : SizedBox(width: 15),
            // const SizedBox(width: 15),
            Icon(Icons.file_download_outlined, size: 16, color: Colors.white),
          ],
        ),
      ),
    );
  }

  Widget buildDocPrevPolicy(BuildContext context, bool isMobile) {
    return GestureDetector(
      onTap: () {
        print("Upload $selectedEnquiryId");
        final selectedId = selectedEnquiryId;
        // final path =
        //     'agent/downloadAgentIncentiveFile?id=$selectedId';
        final path =
            'enquiry/downloadEnquiryFile?enquiry_id=$selectedId&file_type=previous_policy';
        apiService.getPdfDownload(path, selectedId);
      },
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: const Color(0xFF425B5B),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "Download Previous Policy",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w200,
                color: Colors.white,
              ),
            ),
            ?isMobile ? null : SizedBox(width: 15),
            // isMobile ? const Spacer() : const SizedBox(width: 15),
            Icon(Icons.file_download_outlined, size: 16, color: Colors.white),
          ],
        ),
      ),
    );
  }

  Widget buildDocQuotation(BuildContext context, bool isMobile) {
    return GestureDetector(
      onTap: () {
        print("Upload $selectedEnquiryId");
        final selectedId = acceptedQuotationId;
        // final path =
        //     'agent/downloadAgentIncentiveFile?id=$selectedId';
        // final path =
        //     'enquiry/downloadEnquiryFile?enquiry_id=$selectedId&file_type=previous_policy';
        final path =
            'quotation/downloadAdditionalUploadedFile?id=$acceptedQuotationId';

        apiService.getPdfDownload(path, selectedId);
      },
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: const Color(0xFF425B5B),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "Proposal Documents",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w200,
                color: Colors.white,
              ),
            ),
            ?isMobile ? null : SizedBox(width: 15),
            // isMobile ? const Spacer() : const SizedBox(width: 15),
            Icon(Icons.file_download_outlined, size: 16, color: Colors.white),
          ],
        ),
      ),
    );
  }

  Widget buildFormFields(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          // if (docUploadedPDFFileUrlFromApi == null ||
          //     docUploadedPDFFileUrlFromApi!.isEmpty) ...[
          //   Text('No Data Found'),
          // ],

          // Show form fields when URL is NOT null AND NOT empty
          // if (docUploadedPDFFileUrlFromApi != null &&
          //     docUploadedPDFFileUrlFromApi!.isNotEmpty) ...[

          // if (selectedBrokerName != null) ...[
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              // border: Border.all(color: const Colors.bla),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Basic Information', style: headingSTyles),
                Divider(thickness: 0.1, color: Color(0xFF2E7D6E)),
                Row(
                  children: [
                    policynumber(context),
                    SizedBox(width: 20),

                    Insuredname(context),
                    SizedBox(width: 20),
                    registerNumber(context),
                    SizedBox(width: 20),
                    buildPremiumAmount(context),
                    SizedBox(width: 20),
                    Paymentmode(context),
                    SizedBox(width: 20),
                    buildInsurer(context),
                  ],
                ),
                Row(
                  children: [
                    buildAgentName(context),
                    SizedBox(width: 20),
                    buildBroker(context),
                    SizedBox(width: 20),
                    policyissuedate(context),
                    SizedBox(width: 20),
                    policystartdate(context),
                    SizedBox(width: 20),
                    policyenddate(context),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              // border: Border.all(color: const Colors.bla),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,

              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [Text('Premium Breakdown', style: headingSTyles)],
                ),
                Divider(thickness: 0.1, color: Color(0xFF2E7D6E)),

                Container(
                  // color: Colors.blue.shade100,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        // color: Colors.amber,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            buildThirdParty(context),
                            buildOwnDamage(context),
                            buildPersonalAccident(context),
                          ],
                        ),
                      ),

                      SizedBox(width: 20),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          buildCGST(context),
                          buildSGST(context),
                          buildIGST(context),
                          buildPremiumTotal(context),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              // border: Border.all(color: const Colors.bla),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Vehicle Details', style: headingSTyles),
                Divider(thickness: 0.1, color: Color(0xFF2E7D6E)),
                Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    buildMake(context),
                    SizedBox(width: 20),
                    buildModel(context),
                    SizedBox(width: 20),
                    buildVehicleType(context),
                    SizedBox(width: 20),
                    buildFuelType(context),
                    SizedBox(width: 20),
                    buildEngineNo(context),
                    SizedBox(width: 20),
                    buildChassisNo(context),
                  ],
                ),
                SizedBox(height: 10),
                Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    buildCubicCapacity(context),
                    SizedBox(width: 20),
                    buildWeight(context),
                    SizedBox(width: 20),
                    buildYearOfManufacture(context),
                    SizedBox(width: 20),
                    buildDateOfRegistration(context),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 20),

          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 14,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  // border: Border.all(color: const Colors.bla),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('RTO Details', style: headingSTyles),
                    Divider(thickness: 0.1, color: Color(0xFF2E7D6E)),
                    Row(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        buildRTOStateCode(context),
                        SizedBox(width: 20),
                        buildRTOCityCode(context),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(width: 20),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 14,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  // border: Border.all(color: const Colors.bla),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Commission Details', style: headingSTyles),
                    Divider(thickness: 0.1, color: Color(0xFF2E7D6E)),
                    Row(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        buildCommissonAmount(context),
                        SizedBox(width: 20),
                        buildCommissonAppliedRule(context),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              InkWell(
                onTap: () {
                  handleSave();
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 45.0, vertical: 8),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.0),
                    color: Color(0xFF425B5B),
                  ),
                  child: Text(
                    // !hasPolicyData ? 'Submit' : 'Update',
                    'Submit',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
          // ],
        ],
        // ],
      ),
    );
  }

  Widget _buildResponsiveRow(
    BuildContext context,
    Widget first,
    Widget second,
    Widget third,
    Widget fourth,
    // Widget fifth,
    // Widget Six,
  ) {
    if (ResponsiveLayout.isMobile(context)) {
      // Stack vertically
      return Column(children: [first, const SizedBox(height: 2), second]);
    } else {
      // Place side by side
      return Row(
        children: [
          Expanded(child: first),
          const SizedBox(width: 20),
          Expanded(child: second),
          const SizedBox(width: 20),
          Expanded(child: third),
          const SizedBox(width: 20),
          Expanded(child: fourth),
          // const SizedBox(width: 20),
          // Expanded(child: fifth),
          // const SizedBox(width: 20),
          // Expanded(child: Six),
        ],
      );
    }
  }

  Widget registerNumber(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Vehicle Number*', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['regNum']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          // validator: (value) => Validators.phone(value, "phNumber"),
          readOnly: true,
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildInsurer(BuildContext context, {fromHeader = true}) {
    Map<String, dynamic>? selectedInsurerd = filteredInsurersData.firstWhere(
      (item) => item['id'].toString() == selectedInsurer,
      orElse: () => {},
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Insurer *', style: _textStyle),

        SizedBox(height: 5),
        Container(
          height: 30,
          width: MediaQuery.of(context).size.width * 0.12,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyInsurerEnqAsgn,
            selectedItem: selectedInsurerd.isNotEmpty ? selectedInsurerd : null,
            // items: (filter, infiniteScrollProps) {
            //   return filteredInsurersData;
            // },
            // 👇 Enable async filtering based on user input
            items: (filter, infiniteScrollProps) async {
              if (filter.isEmpty) {
                return filteredInsurersData;
              }
              return filteredInsurersData.where((item) {
                return item['name'].toString().toLowerCase().contains(
                  filter.toLowerCase(),
                );
              }).toList();
            },
            itemAsString: (val) => val['name'].toString(), // what to show
            compareFn: (item, selectedItem) =>
                item['id'] == selectedItem['id'], // ✅ compare by id
            validator: (val) {
              if (val == null) {
                return "Required"; // ✅ error message
              }
              return null;
            },
            suffixProps: DropdownSuffixProps(
              // make sure the dropdown button is visible
              dropdownButtonProps: DropdownButtonProps(
                isVisible: true,
                padding: EdgeInsets.zero, // remove default padding
                constraints: const BoxConstraints(
                  // shrink icon tap area
                  minWidth: 12,
                  minHeight: 12,
                ),
                iconSize: 15, // smaller icon
                // icon: const Icon(Icons.arrow_drop_down),
              ),
            ),
            dropdownBuilder: (context, selectedItem) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null ? selectedItem['name'].toString() : "",
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Insurer",
                  ).copyWith(
                    filled: true,
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                  ),
            ),

            popupProps: PopupProps.menu(
              fit: FlexFit.loose,
              searchDelay: Duration(milliseconds: 200),
              constraints: BoxConstraints(maxHeight: 250),
              menuProps: MenuProps(
                backgroundColor:
                    Colors.white, // 👈 sets dropdown background to white
              ),
              showSearchBox: true,
              searchFieldProps: TextFieldProps(
                autofocus: true,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(1),
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Search Insurer...",
                  hintStyle: GoogleFonts.inter(
                    fontSize: 11,
                    color: Colors.black,
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                    ), // 👈 Normal border
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1.5,
                    ), // 👈 Focused border
                  ),
                ),
              ),

              itemBuilder: (context, item, isDisabled, isSelected) {
                return Container(
                  // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 3,
                  ),
                  child: Text(
                    item['name'].toString(),
                    style: GoogleFonts.inter(fontSize: 12, color: Colors.black),
                  ),
                );
              },
              // constraints: BoxConstraints(),
            ),

            onChanged: (val) {
              if (val != null) {
                print("Selected Insurer : ${val['name']}");
                print("Id: ${val['id']}");
                selectedInsurer = val['id'];
                // controllers['agentId']?.text = val['agent_code'];
                // agentId = agent['id'];
              }
            },
          ),
        ),
      ],
    );
  }

  Widget buildIdv(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('IDV *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['idv']!,
          readOnly: true,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.26,
        ),
      ],
    );
  }

  Widget buildPremiumAmount(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Premium Amount *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['premium_amount']!,
          readOnly: true,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.doubleNumber(value, "Premium Amount"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildPlanType(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Plan Type *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['planType']!,
          readOnly: true,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.26,
        ),
      ],
    );
  }

  Widget Insuredname(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Insured Name *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['policyInsName']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.requiredField(value, "policyInsName"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }
  //
  // Widget premiumamount(BuildContext context) {
  //   return Column(
  //     crossAxisAlignment: CrossAxisAlignment.start,
  //     children: [
  //       Text('Premium Amount ', style: _textStyle),
  //       SizedBox(height: 10),
  //       ThemedFormField(
  //         controller: controllers['premium_amount']!,
  //         // validator: (value) =>
  //         //     Validators.requiredField(value, "policyPremiumAmount"),
  //         txtwidth: ResponsiveLayout.isMobile(context)
  //             ? null
  //             : MediaQuery.of(context).size.width * 0.26,
  //       ),
  //     ],
  //   );
  // }

  Widget policynumber(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Policy Number ', style: _textStyle),
        SizedBox(height: 5),
        ThemedFormField(
          controller: controllers['policyNumber']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          // validator: (value) => Validators.requiredField(value, "policyNumber"),
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z 0-9]')),
          ],
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildBroker(BuildContext context) {
    Map<String, dynamic>? selectedBrokers = filteredBrokerData.firstWhere(
      (item) => item['id'].toString() == selectedBroker,
      orElse: () => {},
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Broker *', style: _textStyle),
        SizedBox(width: 10),
        // SizedBox(
        //   width: MediaQuery.of(context).size.width * 0.095,
        //   child: Text(
        //     '$selectedBrokerName',
        //     style: GoogleFonts.inter(fontSize: 12),
        //   ),
        // ),
        SizedBox(
          height: 30,
          width: MediaQuery.of(context).size.width * 0.12,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyBroker,
            selectedItem: selectedBrokers.isNotEmpty ? selectedBrokers : null,
            items: (filter, infiniteScrollProps) {
              return filteredBrokerData;
            },

            itemAsString: (val) => val['name'].toString(), // what to show
            compareFn: (item, selectedItem) =>
                item['id'] == selectedItem['id'], // ✅ compare by id
            validator: (val) {
              if (val == null) {
                return "Required"; // ✅ error message
              }
              return null;
            },
            suffixProps: DropdownSuffixProps(
              // make sure the dropdown button is visible
              dropdownButtonProps: DropdownButtonProps(
                isVisible: true,
                padding: EdgeInsets.zero, // remove default padding
                constraints: const BoxConstraints(
                  // shrink icon tap area
                  minWidth: 12,
                  minHeight: 12,
                ),
                iconSize: 15, // smaller icon
                // icon: const Icon(Icons.arrow_drop_down),
              ),
            ),
            dropdownBuilder: (context, selectedItem) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null ? selectedItem['name'].toString() : "",
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Select Broker",
                  ).copyWith(
                    filled: true,
                    // errorStyle: const TextStyle(
                    //   fontSize: 9,
                    //
                    //   // height: 0.0
                    // ),
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                  ),
            ),

            popupProps: PopupProps.menu(
              fit: FlexFit.loose,
              constraints: BoxConstraints(maxHeight: 250),
              menuProps: MenuProps(
                backgroundColor:
                    Colors.white, // 👈 sets dropdown background to white
              ),
              showSearchBox: true,
              searchFieldProps: TextFieldProps(
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Search Broker...",
                  hintStyle: GoogleFonts.inter(
                    fontSize: 12,
                    color: Colors.black,
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                    ), // 👈 Normal border
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1.5,
                    ), // 👈 Focused border
                  ),
                ),
              ),

              itemBuilder: (context, item, isDisabled, isSelected) {
                return Container(
                  // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 3,
                  ),
                  child: Text(
                    item['name'].toString(),
                    style: GoogleFonts.inter(fontSize: 12, color: Colors.black),
                  ),
                );
              },
              // constraints: BoxConstraints(),
            ),

            onChanged: (val) {
              if (val != null) {
                print("Selected Broker : ${val['name']}");
                print("Id: ${val['id']}");
                selectedBroker = val['id'];
                setState(() {
                  selectedBrokerName = val['name'];
                  print('selectedBrokerName - $selectedBrokerName');
                });
                // controllers['agentId']?.text = val['agent_code'];
                // agentId = agent['id'];
              }
            },
          ),
        ),
      ],
    );
  }

  Widget buildAgentName(BuildContext context, {fromHeader = true}) {
    Map<String, dynamic>? selectedAgntName = filteredAgentData.firstWhere(
      (item) => item['id'].toString() == selectedAgent,
      orElse: () => {},
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Partner *', style: _textStyle),

        SizedBox(height: 5),
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          // width: fromHeader
          //     ? MediaQuery.of(context).size.width * 0.11
          //     : MediaQuery.of(context).size.width * 0.08,
          height: 30,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyAgent,
            selectedItem: selectedAgntName.isNotEmpty ? selectedAgntName : null,
            // items: (filter, infiniteScrollProps) {
            //   return filteredAgentData;
            // },
            items: (filter, infiniteScrollProps) async {
              if (filter.isEmpty) {
                return filteredAgentData;
              }
              return filteredAgentData.where((item) {
                return item['name'].toString().toLowerCase().contains(
                  filter.toLowerCase(),
                );
              }).toList();
            },

            itemAsString: (val) => val['name'].toString(), // what to show
            compareFn: (item, selectedItem) =>
                item['id'] == selectedItem['id'], // ✅ compare by id
            validator: (val) {
              if (val == null) {
                return "Required"; // ✅ error message
              }
              return null;
            },
            suffixProps: DropdownSuffixProps(
              // make sure the dropdown button is visible
              dropdownButtonProps: DropdownButtonProps(
                isVisible: true,
                padding: EdgeInsets.zero, // remove default padding
                constraints: const BoxConstraints(
                  // shrink icon tap area
                  minWidth: 12,
                  minHeight: 12,
                ),
                iconSize: 15, // smaller icon
                // icon: const Icon(Icons.arrow_drop_down),
              ),
            ),
            dropdownBuilder: (context, selectedItem) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null
                    ? selectedItem['name'].toString()
                    : "", // ✅ FIXED
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Partner Name",
                  ).copyWith(
                    filled: true,
                    // errorStyle: const TextStyle(
                    //   fontSize: 9,
                    //
                    //   // height: 0.0
                    // ),
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                  ),
            ),

            popupProps: PopupProps.menu(
              fit: FlexFit.loose,
              constraints: BoxConstraints(maxHeight: 250),
              menuProps: MenuProps(
                backgroundColor:
                    Colors.white, // 👈 sets dropdown background to white
              ),
              showSearchBox: true,

              searchFieldProps: TextFieldProps(
                autofocus: true,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(1),
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Partner Name",
                  hintStyle: GoogleFonts.inter(
                    fontSize: 10,
                    color: Colors.grey,
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                    ), // 👈 Normal border
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1.5,
                    ), // 👈 Focused border
                  ),
                ),
              ),

              // constraints: BoxConstraints(),
              itemBuilder: (context, item, isDisabled, isSelected) {
                return Container(
                  // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 3,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        item['name'].toString(),
                        style: GoogleFonts.inter(
                          fontSize: 12,
                          color: Colors.black,
                        ),
                      ),
                      Text(
                        item['agent_code'].toString(),
                        style: GoogleFonts.inter(
                          fontSize: 11,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),

            onChanged: (val) {
              if (val != null) {
                print("Selected Partner : ${val['name']}");
                print("Id: ${val['id']}");
                selectedAgent = val['id'];
                // controllers['agentId']?.text = val['agent_code'];
                // agentId = agent['id'];
              }
            },
          ),
        ),
      ],
    );
  }

  Widget Paymentmode(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text('Payment Mode *', style: _textStyle),
        SizedBox(width: 15),
        // SizedBox(
        //   width: MediaQuery.of(context).size.width * 0.075,
        //   child: Text(
        //     selectedPaymentMode,
        //     // controllers['policyPaymentMode']!.text,
        //     style: GoogleFonts.inter(fontSize: 12),
        //   ),
        // ),
        ThemedFormField(
          controller: controllers['policyPaymentMode']!,

          // borderColor: Colors.white,
          // highlightColor: Colors.white,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          errorBorderColor: Color(0xffEDF6F5),
          hintText: 'Online / Cash',
          // borderColor: Color(0xffEDF6F5),
          readOnly: true,
          validator: (value) =>
              Validators.requiredField(value, "policyPaymentMode"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget policyissuedate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Issue Date', style: _textStyle),
        SizedBox(height: 10),
        ThemedDateField(
          hintText: "Select Date",
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
          // backgroundColor: const Color(0xFFECECEC),
          // validator: (value) => Validators.requiredField(value, "date"),
          controller: controllers['issueDate']!,
          onDateSelected: (date) {
            print("Picked Date: $date");

            controllers['issueDate']?.text = DateFormat(
              'dd-MM-yyyy',
            ).format(date);
            //  controllers['date']?.text = date as String;
          },
        ),
      ],
    );
  }

  Widget policystartdate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Start Date', style: _textStyle),
        SizedBox(height: 10),
        ThemedDateField(
          hintText: "Select Date",
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
          // backgroundColor: const Color(0xFFECECEC),
          // validator: (value) => Validators.requiredField(value, "date"),
          controller: controllers['startDate']!,
          onDateSelected: (date) {
            print("Picked Date: $date");

            controllers['startDate']?.text = DateFormat(
              'dd-MM-yyyy',
            ).format(date);

            // auto set end date (1 year later - 1 day if needed)
            final endDate = DateTime(
              date.year + 1,
              date.month,
              date.day,
            ).subtract(const Duration(days: 1)); // optional: subtract 1 day

            controllers['endDate']?.text = DateFormat(
              'dd-MM-yyyy',
            ).format(endDate);

            print("Auto-set End Date: $endDate");
            //  controllers['date']?.text = date as String;
          },
        ),
      ],
    );
  }

  Widget policyenddate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('End Date', style: _textStyle),
        SizedBox(height: 10),
        ThemedDateField(
          hintText: "Select Date",
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
          // backgroundColor: const Color(0xFFECECEC),
          // validator: (value) => Validators.requiredField(value, "date"),
          validator: (value) {
            // if (value == null || value.isEmpty) {
            //   return "Required";
            // }

            final startDateControllerText = controllers['startDate']?.text;
            if (startDateControllerText == null ||
                startDateControllerText.isEmpty) {
              return "Select start date first";
            }

            final startDate = DateFormat(
              'dd-MM-yyyy',
            ).parse(startDateControllerText);
            final endDate = DateFormat('dd-MM-yyyy').parse(value!);

            if (endDate.isBefore(startDate)) {
              return "End date cannot be before start date";
            }

            // Minimum end date = start date + 1 year - 1 day (or just +1 year)
            final minEndDate = DateTime(
              startDate.year + 1,
              startDate.month,
              startDate.day,
            ).subtract(const Duration(days: 1));

            if (endDate.isBefore(minEndDate)) {
              return "End date must be at least 1 year from start date";
            }

            return null;

            // final startDateControllerText = controllers['startDate']?.text;
            // if (startDateControllerText == null ||
            //     startDateControllerText.isEmpty) {
            //   return "Select start date first";
            // }
            //
            // final startDate = DateFormat(
            //   'dd-MM-yyyy',
            // ).parse(startDateControllerText);
            // final endDate = DateFormat('dd-MM-yyyy').parse(value);
            //
            // if (endDate.isBefore(startDate)) {
            //   return "End date cannot be before start date";
            // }
            //
            // final expectedEndDate = DateTime(
            //   startDate.year + 1,
            //   startDate.month,
            //   startDate.day,
            // ).subtract(const Duration(days: 1));
            //
            // if (endDate != expectedEndDate) {
            //   return "End date must be exactly 1 year from start date";
            // }
            //
            // return null; // valid
          },
          controller: controllers['endDate']!,
          onDateSelected: (date) {
            print("Picked Date: $date");

            controllers['endDate']?.text = DateFormat(
              'dd-MM-yyyy',
            ).format(date);
            _formKey.currentState?.validate();
            //  controllers['date']?.text = date as String;
          },
        ),
      ],
    );
  }

  Widget buildUploadPolicyPdf(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.15,
          child: Text('Upload Policy PDF * ', style: _textStyle),
        ),
        // const SizedBox(height: 10),
        // SizedBox(width: 20),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ThemedUploadField(
              hintText: selectedPDFFileNames ?? "Upload Document",
              allowedExtensions: ['pdf'],
              // backgroundColor: Colors.white,
              backgroundColor: Color(0xffEDF6F5),
              txtheight: 35,
              txtwidth: ResponsiveLayout.isMobile(context)
                  ? null
                  : (docUploadedPDFFileUrlFromApi != null)
                  ? MediaQuery.of(context).size.width * 0.117
                  // ? MediaQuery.of(context).size.width * 0.135
                  // ? MediaQuery.of(context).size.width * 0.12
                  : MediaQuery.of(context).size.width * 0.14,
              // : MediaQuery.of(context).size.width * 0.15,
              // backgroundColor: Color(0xFFEDF6F5),
              onFileSelected: (fileName, file) async {
                print("Picked file: $fileName (${file.size} bytes)");

                if (!fileName.toLowerCase().endsWith('.pdf')) {
                  ToastHelper.showErrorToast(
                    context,
                    'Only PDF files are allowed.',
                  );
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('Only PDF files are allowed.'),
                      backgroundColor: Colors.red,
                    ),
                  );
                  return; // Stop here
                }

                print("Picked file: $fileName (${file.size} bytes)");
                setState(() {
                  docPDFUploadedFile = file;
                });

                // if (selectedBrokerName == 'Nhance') {
                //   handleUploadPolicy();
                // }
              },
            ),

            if (docUploadedPDFFileUrlFromApi != null) ...[
              const SizedBox(width: 5),
              Tooltip(
                message: 'Download',
                // color: Colors.white,
                child:
                    // Row(
                    //               mainAxisSize: MainAxisSize.min,
                    //               mainAxisAlignment: MainAxisAlignment.end,
                    //               children: [
                    InkWell(
                      onTap: () => apiService.downloadFile(
                        apiUrl:
                            'policy/downloadPolicyFile?policy_id=$choosedPolcyId&file_type=policy_pdf',
                        apiId: choosedPolcyId,
                        localFile: docPDFUploadedFile,
                        fileName: selectedPDFFileNames,
                      ),

                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 5,
                          vertical: 8,
                        ),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5),
                          color: Color(0xFF425B5B),
                          // color: Colors.green.shade300,
                        ),
                        child: Row(
                          children: const [
                            // Text(
                            //   "Download",
                            //   style: TextStyle(
                            //     fontSize: 12,
                            //     fontWeight: FontWeight.w200,
                            //     color: Colors.white,
                            //   ),
                            // ),
                            // SizedBox(width: 5),
                            Icon(Icons.download, size: 13, color: Colors.white),
                          ],
                        ),
                      ),
                    ),
                //   ],
                // ),
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget buildUploadPolicyReceipt(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Upload Policy Receipt *', style: _textStyle),
        const SizedBox(height: 10),
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ThemedUploadField(
              hintText: selectedFileNames ?? "Upload Document",
              txtwidth: ResponsiveLayout.isMobile(context)
                  ? null
                  : MediaQuery.of(context).size.width * 0.26,
              // backgroundColor: Color(0xFFEDF6F5),
              onFileSelected: (fileName, file) {
                print("Picked file: $fileName (${file.size} bytes)");
                setState(() {
                  docUploadedFile = file;
                });
              },
            ),
            const SizedBox(height: 5),

            if (docUploadedFileUrlFromApi != null)
              Container(
                // color: Colors.white,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () => apiService.downloadFile(
                        apiUrl:
                            'policy/downloadPolicyFile?policy_id=$choosedPolcyId&file_type=policy_payment_receipt',
                        apiId: choosedPolcyId,
                        localFile: docUploadedFile,
                        fileName: selectedFileNames,
                      ),
                      child: Container(
                        padding: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5),
                          color: Color(0xFF425B5B),
                          // color: Colors.green.shade300,
                        ),
                        child: Row(
                          children: const [
                            Text(
                              "Download",
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w200,
                                color: Colors.white,
                              ),
                            ),
                            SizedBox(width: 5),
                            Icon(Icons.download, size: 13, color: Colors.white),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
      ],
    );
  }

  Widget buildResponsiveUploadField({
    String? label, // 🔹 make optional
    required String? hintText,
    required void Function(String fileName, dynamic file) onFileSelected,
  }) {
    final isMobile = ResponsiveLayout.isMobile(context);

    final uploadWidget = ThemedUploadField(
      hintText: hintText ?? "Upload Documents",
      txtwidth: isMobile ? null : MediaQuery.of(context).size.width * 0.26,
      onFileSelected: onFileSelected,
    );

    if (isMobile) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (label != null && label.isNotEmpty) ...[
            // ✅ only render if label is given
            Text(label, style: _textStyle),
            const SizedBox(height: 8),
          ],
          uploadWidget,
          const SizedBox(height: 16),
        ],
      );
    } else {
      return Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (label != null && label.isNotEmpty) ...[
            Expanded(child: Text(label, style: _textStyle)),
            const SizedBox(width: 10),
          ],
          uploadWidget,
        ],
      );
    }
  }

  // NEW FIELDs

  Widget buildThirdParty(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('Third Party', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['tp']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            // validator: (value) => Validators.requiredField(value, "Third Party"),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            // onChanged: (value) => calculateAmount(),
            onChanged: (v) {
              print('pa onChanged -> $v'); // should show on every keystroke
              calculateAmount();
            },
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.12,
          ),
        ),
      ],
    );
  }

  Widget buildOwnDamage(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('Own Damage ', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['od']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            // validator: (value) => Validators.requiredField(value, "OwnDamage"),
            onChanged: (value) => calculateAmount(),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.12,
          ),
        ),
      ],
    );
  }

  Widget buildPersonalAccident(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('Personal Accident', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['pa']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            onChanged: (value) => calculateAmount(),
            // validator: (value) =>
            //     Validators.requiredField(value, "PersonalAccident"),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.12,
          ),
        ),
      ],
    );
  }

  Widget buildCGST(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('CGST', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['cgst']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            validator: (value) => Validators.requiredField(value, "CGST"),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
          ),
        ),
      ],
    );
  }

  Widget buildSGST(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('SGST', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['sgst']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            validator: (value) => Validators.requiredField(value, "SGST"),
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
          ),
        ),
      ],
    );
  }

  Widget buildIGST(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('IGST', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['igst']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            validator: (value) => Validators.requiredField(value, "IGST"),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
          ),
        ),
      ],
    );
  }

  Widget buildPremiumTotal(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.12,
          child: Text('Total Premium *', style: _textStyle),
        ),
        SizedBox(width: 20),
        SizedBox(
          height: 35,
          child: ThemedFormField(
            controller: controllers['premiumTOT']!,
            // backgroundColor: Color(0xffEDF6F5),
            errorBorderColor: Color(0xffEDF6F5),
            hintText: '0',
            validator: (value) => Validators.requiredField(value, "premium"),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'[.0-9]')),
            ],
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
          ),
        ),
      ],
    );
  }

  Widget buildRTOStateCode(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('RTO State Code *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['rto_state_code']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.requiredField(value, "RTO State Code"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildRTOCityCode(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('RTO City Code *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['rto_city_code']!,
          validator: (value) =>
              Validators.requiredField(value, "RTO City Code"),
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildCommissonAmount(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Commission Amount', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['commison_amount']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          // validator: (value) =>
          //     Validators.requiredField(value, "RTO City Code"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildCommissonAppliedRule(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Commission Applied Rule', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['commison_applied_rule']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          // validator: (value) =>
          //     Validators.requiredField(value, "RTO City Code"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildWeight(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Weight *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['weight']!,
          validator: (value) => Validators.requiredField(value, "weight"),
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildFuelType(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Fuel Type *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['fuel_type']!,
          validator: (value) => Validators.requiredField(value, "Fuel Type"),
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildDateOfRegistration(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Date Of Registration *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['date_of_registration']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.requiredField(value, "Date Of Registration"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildYearOfManufacture(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Year Of Manufacture *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['year_of_manufacture']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.requiredField(value, "Year Of Manufacture"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildEngineNo(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Engine No *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['engine_no']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) => Validators.requiredField(value, "Engine No"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildChassisNo(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Chassis No *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['chassis_no']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) => Validators.requiredField(value, "Chassis No"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildMake(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Make *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['make']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) => Validators.requiredField(value, "Make"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildModel(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Model *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['model']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) => Validators.requiredField(value, "Model"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildCubicCapacity(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Cubic Capacity *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['cubic_capacity']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) =>
              Validators.requiredField(value, "Cubic Capacity"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildVehicleType(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Vehicle Type *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['vehicle_type']!,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          validator: (value) => Validators.requiredField(value, "Vehicle Type"),
          txtheight: 30,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
        ),
      ],
    );
  }

  Widget buildResponsiveField({required String label, required Widget field}) {
    final isMobile = ResponsiveLayout.isMobile(context);

    if (isMobile) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: _textStyle),
          const SizedBox(height: 8),
          field,
          const SizedBox(height: 16),
        ],
      );
    } else {
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: Text(label, style: _textStyle)),
          const SizedBox(width: 10),
          field,
        ],
      );
    }
  }

  static final _textStyle = GoogleFonts.poppins(
    fontSize: 11,
    color: Color(0XFF334155),
    fontWeight: FontWeight.w500,
  );

  static final headingSTyles = GoogleFonts.poppins(
    fontSize: 12.5,
    // color: Color(0XFF334155),
    color: Color(0xFF2E7D6E),
    fontWeight: FontWeight.w600,
  );
  static const _textStrongStyle = TextStyle(
    fontSize: 12,
    fontWeight: FontWeight.w800,
  );
}
