import 'dart:convert';

import 'package:dropdown_search/dropdown_search.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.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/staff/policy/policyPdf.dart';
import 'package:pdf_render/pdf_render_widgets.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';

import '../../../../core/config/env.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/toastNotification.dart';
import '../../../../data/utils/validators.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';

import '../../../providers/userRoleProvider.dart';
import '../../../themes/indicators/customizd_file_upload.dart';
import '../../../themes/indicators/input_field_decoration.dart';
import '../../../screens/staff/policy/loadNetworkPdfBytes.dart';
import 'dart:typed_data';

import 'package:flutter/services.dart';

import '../../../themes/indicators/search_field_theme.dart';
import '../../../themes/indicators/text_field_theme.dart';

final digitsOnlyFormatter = [FilteringTextInputFormatter.digitsOnly];

final decimalFormatter = [
  FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}$')),
];

class endorsomentValidation extends ConsumerStatefulWidget {
  final String title;
  final dynamic userId;
  final dynamic managerId;
  final dynamic role;
  final dynamic item;
  final void Function(String value) onSubmit;

  const endorsomentValidation({
    super.key,
    required this.title,
    required this.onSubmit,
    required this.userId,
    required this.managerId,
    required this.item,
    required this.role,
  });
  @override
  ConsumerState<endorsomentValidation> createState() =>
      _endorsomentValidationState();
}

class _endorsomentValidationState extends ConsumerState<endorsomentValidation> {
  String? _cachedPdfUrl;
  String? pdfUrl; // full file path from API
  late ApiService apiService;
  bool isLoading = false;
  bool isSubmitLoading = false;

  dynamic userId;
  dynamic roleId;
  dynamic managerId;

  String lifecycleStatus = "Open"; // default
  String verificationStatus = "To Verify"; // default

  late TextEditingController controller;
  Map<String, TextEditingController> controllers = {};

  String? _token;
  String? selectedClaimFileNames;
  String? selectedEndorsement;
  String? selectedEndrosementPolicyFrom;
  String? selectedFileNames;

  String? selectedPaymentModeId;

  bool isPolicyFromFocused = false;
  bool isEndorsementTypeFocused = false;
  bool isInsurerFocused = false;
  bool isBrokerFocused = false;
  bool isPolicyNumberFocused = false;

  bool isRegNoFocused = false;
  bool isInsuredNameFocused = false;
  bool isEndorsementNoFocused = false;
  bool isContactPersonFocused = false;
  bool isPendingDaysFocused = false;
  bool isPremiumFocused = false;
  bool isCommissionFocused = false;
  bool isStartDateFocused = false;
  bool isEndDateFocused = false;
  bool isPaymentModeFocused = false;

  String policyFrom = "";
  String financialOrNonFinancial = "";

  bool isPolicyNumberReadOnly = true;

  PlatformFile? uploadedFile;

  final _formKeyClaims = GlobalKey<FormState>();
  final _formKeyEndrosment = GlobalKey<FormState>();
  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKey =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();
  final GlobalKey<DropdownSearchState<Map<String, dynamic>>>
  dropDownKeyEndorsement =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  final TextEditingController _vehicleSearchController =
      TextEditingController();
  final TextEditingController _policySearchController = TextEditingController();

  /// Controllers
  final TextEditingController policyNumber = TextEditingController();
  final TextEditingController endorsementDescription = TextEditingController();
  final TextEditingController contactPerson = TextEditingController();
  final TextEditingController pendingDays = TextEditingController();
  final TextEditingController premium = TextEditingController();
  final TextEditingController commission = TextEditingController();
  // 🔹 NEW CONTROLLERS
  final TextEditingController regNoController = TextEditingController();
  final TextEditingController insuredNameController = TextEditingController();
  final TextEditingController endorsementNoController = TextEditingController();
  final TextEditingController contactPersonController = TextEditingController();
  // final TextEditingController pendingDaysController = TextEditingController();
  final TextEditingController premiumController = TextEditingController();
  final TextEditingController commissionController = TextEditingController();
  final TextEditingController policyStartController = TextEditingController();
  final TextEditingController policyEndController = TextEditingController();

  // 🔹 DROPDOWN VALUES
  String? selectedInsurer;
  String? selectedBroker;
  String? selectedEndorsementNo;
  // String? selectedInsuredName;
  String financialType = "Yes";

  // 🔹 LISTS
  List<Map<String, dynamic>> insurerList = [];
  List<Map<String, dynamic>> brokerList = [];
  List<Map<String, dynamic>> endorsementNoList = [];
  List<Map<String, dynamic>> insuredNameList = [];

  PlatformFile? docUploadedFile;
  PlatformFile? docUploadedEndorsFile;

  List<Map<String, dynamic>> getEndrosmentType = [];
  List<Map<String, dynamic>> filteredEndrosmentData = [];

  List<Map<String, dynamic>> getPolicyListData = [];
  List<Map<String, dynamic>> originalPolicyData = [];
  List<Map<String, dynamic>> filteredPolicyData = [];

  List<Map<String, dynamic>> getVehicleListData = [];
  List<Map<String, dynamic>> originalVehicleData = [];
  List<Map<String, dynamic>> filteredVehicleData = [];

  List<Map<String, dynamic>> getPolicyData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];

  List<Map<String, dynamic>> getPaymentModeData = [];
  List<Map<String, dynamic>> filteredPaymentModeData = [];

  final List<Map<String, dynamic>> policyFromOptions = [
    {"policy_from": "Internal"},
    {"policy_from": "External"},
  ];

  bool isInternal = false;
  bool isExternal = false;
  bool showFinancialFields = true;

  final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();

  Map<String, dynamic> endrosmentDetails() {
    Map<String, dynamic> data = {
      "policy_number": controllers["policyNum"]?.text,
      "endorsement_type": selectedEndorsement,
      "policy_from": selectedEndrosementPolicyFrom,
      "manager_id": widget.managerId,
      "updated_by": widget.userId,
      "id": widget.item?['id'],
      "endorsement_description": controllers["remarks"]?.text,
      "status": lifecycleStatus,
    };

    if (isInternal) {
      data.addAll({
        "endorsement_no": endorsementNoController.text,
        "contact_person": contactPersonController.text,
        // "pending_days": pendingDaysController.text,
        "financia_or_non_financial": financialType,
        "payment_mode_id": selectedPaymentModeId,
      });

      if (showFinancialFields) {
        data.addAll({
          "endorsement_premium": premiumController.text,
          "commission_amount": commissionController.text,
        });
      }
    }

    if (isExternal) {
      data.addAll({
        "endorsement_no": endorsementNoController.text,
        "contact_person": contactPersonController.text,
        // "pending_days": pendingDaysController.text,
        "financia_or_non_financial": financialType,

        "insurer_id": selectedInsurer,
        "insured_name": insuredNameController.text,
        "policy_start_date": policyStartController.text,
        "policy_end_date": policyEndController.text,
        "reg_no": regNoController.text,
        "broker_id": selectedBroker,
        "endorsement_premium": premiumController.text,
        "commission_amount": commissionController.text,
        "payment_mode_id": selectedPaymentModeId,
      });
    }

    return data;
  }

  bool showExistingFile = false;
  String? existingFileName;

  @override
  void initState() {
    super.initState();

    apiService = ApiService();

    existingFileName = widget.item?['endorsement_file_name'];

    showExistingFile =
        existingFileName != null && existingFileName.toString().isNotEmpty;

    // ✅ INITIALIZE CONTROLLERS MAP
    controllers = {
      'policyNum': TextEditingController(),
      'remarks': TextEditingController(),
      'startDate': TextEditingController(),
      'endDate': TextEditingController(),
    };

    Future.microtask(() async {
      managerId = ref.read(managerIdProvider);
      roleId = ref.read(userRoleProvider);
      userId = ref.read(userIdProvider);

      if (userId != null) {
        await getStaffList(managerId, userId, roleId);
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      setEditValues();
    });

    _initializeToken();
    getPolicyFilePath();
    getEnroementType();
    getBroker();
    getInsurerDetails();
    getPaymentMode();
  }

  @override
  void dispose() {
    _vehicleSearchController.dispose();
    _policySearchController.dispose();

    for (var controller in controllers.values) {
      controller.dispose();
    }

    super.dispose();
  }

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

  void setEditValues() {
    final item = widget.item;

    if (item == null) return;
    final policyFromValue = item['policy_from']?.toString() ?? '';

    setState(() {
      controllers['policyNum']?.text = item['policy_number'] ?? '';
      controllers['remarks']?.text = item['endorsement_description'] ?? '';

      endorsementNoController.text = item['endorsement_no'] ?? '';
      contactPersonController.text = item['contact_person'] ?? '';
      // pendingDaysController.text = item['pending_days']?.toString() ?? '';
      premiumController.text = item['endorsement_premium']?.toString() ?? '';
      commissionController.text = item['commission_amount']?.toString() ?? '';
      selectedPaymentModeId = item['payment_mode_id']?.toString();

      insuredNameController.text = item['insured_name'] ?? '';
      regNoController.text = item['reg_no'] ?? '';
      policyStartController.text = item['policy_start_date'] ?? '';
      policyEndController.text = item['policy_end_date'] ?? '';

      selectedInsurer = item['insurer_id']?.toString();
      selectedBroker = item['broker_id']?.toString();
      selectedEndorsement = item['endorsement_type']?.toString();
      selectedEndrosementPolicyFrom = item['policy_from'];
      lifecycleStatus = item['status'];

      financialType = item['financia_or_non_financial'] ?? "Yes";

      // 🔥 IMPORTANT PART
      isInternal = policyFromValue == "Internal";
      isExternal = policyFromValue == "External";

      showFinancialFields = financialType == "Yes";
    });
  }

  Future<void> getEnroementType() async {
    print('Insurers called');

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

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

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

  Future<void> getPaymentMode() async {
    print('getPaymentMode called');

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

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

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

  // Get Broker List
  Future<void> getBroker() async {
    print('getBroker called');

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

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

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

  Future<void> getInsurerDetails() async {
    try {
      final response = await apiService.fetchMasterDropDown('Insurers');

      print("***999999999999999999*********** $response");

      if (response['status'] == 200) {
        print('getInsurerDetails - ${response['data']}');

        setState(() {
          insurerList = List<Map<String, dynamic>>.from(response['data']);

          // filteredInsurerData =
          // List<Map<String, dynamic>>.from(getInsurerDetailsData);
          //
          // print("Filtered Insurer Data: $filteredInsurerData");
        });
      } else {
        setState(() {
          insurerList = [];
          // filteredInsurerData = [];
        });
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  Future<void> getPolicyListSearchData(String val) async {
    try {
      final response = await apiService.fetchPolicySearch(val);

      if (response['status'] == 'success' && response['data'] != null) {
        final dataList = List<Map<String, dynamic>>.from(response['data']);
        setState(() {
          getPolicyListData = dataList;
          originalPolicyData = dataList;
          filteredPolicyData = List.from(originalPolicyData);
        });
      } else {
        setState(() {
          getPolicyListData = [];
          originalPolicyData = [];
          filteredPolicyData = [];
        });
      }
    } catch (e) {
      print('Exception occurred: $e');
      setState(() {
        getPolicyListData = [];
        originalPolicyData = [];
        filteredPolicyData = [];
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getVehicleListSearchData(String val) async {
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchVehicleSearch(val);

      if (response['status'] == 'success') {
        print('E113 => getStaffListData => ${response['data']}');
        setState(() {
          getVehicleListData = List<Map<String, dynamic>>.from(
            response['data'],
          );
          originalVehicleData = getVehicleListData;
          filteredVehicleData = List.from(originalVehicleData);
          // print('originalData - $getClaimPolicies');
        });
      } else {
        getVehicleListData = [];
        originalVehicleData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getStaffList(
    dynamic managerId,
    role,
    roleId, {
    String fromDate = '',
    String toDate = '',
  }) async {
    print('D68 => Fns called => $managerId | $role');
    setState(() {
      isLoading = true;
    });

    final id = int.parse(managerId);
    // FORCE BOTH VALUES TO STRING
    final String managerIdStr = managerId?.toString() ?? '';
    final String roleStr = role?.toString() ?? '';

    try {
      final response = await apiService.fetchPolicyDataOnlyList(
        managerIdStr,
        roleStr,
        roleStr,
        fromDate: controllers['startDate']?.text ?? '',
        toDate: controllers['endDate']?.text ?? '',
        selectedStaffId: widget.userId ?? '',
      );

      if (response['status'] == 'success') {
        final data = response['data'];
        print('D81 => getStaffListData => ${response['data']}');

        final fromDate = response['from_date'] ?? '';
        final toDate = response['to_date'] ?? '';

        print('FromDate : $fromDate');
        print('ToDate : $toDate');
        setState(() {
          controllers['startDate']?.text = fromDate;
          controllers['endDate']?.text = toDate;
          if (data is List) {
            // Already a list of maps
            getPolicyData = List<Map<String, dynamic>>.from(data);
          } else if (data is Map) {
            // Single object, wrap in a list
            getPolicyData = [Map<String, dynamic>.from(data)];
          } else {
            getPolicyData = [];
          }
          // getStaffData = List<Map<String, dynamic>>.from(response['data']);
          originalData = getPolicyData;
          filteredData = List.from(originalData);
          // print('originalData - $getClaimPolicies');
        });
      } else {
        getPolicyData = [];
        originalData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> getPolicyFilePath() async {
    _pdfViewerKey.currentState?.openBookmarkView();

    final id = widget.item?['id'];
    if (id == null) {
      debugPrint('endorsomentValidation: policy id is null, skipping API call');
      return;
    }

    if (!mounted) return;
    setState(() => isLoading = true);
    try {
      final url = Uri.parse(
        '${Env.apiUrl}endorsement/EndorsementFilePath?endorsement_id=$id',
      );

      setState(() {
        pdfUrl = "$url";
        _cachedPdfUrl = pdfUrl;
      });
      print("FINAL PDF URL -> $pdfUrl");
    } catch (e, st) {
      print('Exception in getPolicyFilePath: $e\n$st');
    } finally {
      if (!mounted) return;
      setState(() => isLoading = false);
    }
  }

  // ================= CREATE API =================

  Future<void> createUserData(data) async {
    if (!mounted) return;

    setState(() {
      isSubmitLoading = true; // 🔥 START LOADER
    });

    final Uri uri = Uri.parse('${Env.apiUrl}endorsement/updateEndorsement');

    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;

    print("USerDAta - $data");

    // userData.forEach((key, value) {
    //   request.fields[key] = value.toString();
    //   print("✅ Encoded travel_details2: ${request.fields[key]}");
    // });

    data.forEach((key, value) {
      // if (key != 'certificate_file_name') {
      request.fields[key] = value.toString();
      print("✅ Encoded $key: ${request.fields[key]}");
      // }
    });
    // Attach file if selected
    if (docUploadedEndorsFile != null) {
      try {
        if (docUploadedEndorsFile!.bytes != null) {
          final multipartFile = http.MultipartFile.fromBytes(
            'endorsement_file_name',
            docUploadedEndorsFile!.bytes!,
            filename: docUploadedEndorsFile!.name,
          );
          request.files.add(multipartFile);
        }
        // else if (docUploadedEndorsFile!.path != null) {
        //   final multipartFile = await http.MultipartFile.fromPath(
        //     'endorsement_file_name',
        //     docUploadedEndorsFile!.path!,
        //     filename: docUploadedEndorsFile!.name,
        //   );
        //   request.files.add(multipartFile);
        // }
        print("📎 File attached: ${docUploadedEndorsFile!.name}");
      } catch (e) {
        print("❌ Failed to attach file: $e");
      }
    }

    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) {
        print("✅ Partner submitted successfully!");

        print("Response: ${response.body}");
        ToastHelper.showSuccessToast(context, 'Saved Successfully');
        context.pop(true);

        widget.onSubmit("success");
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        final responseBody = jsonDecode(response.body);
        dynamic msg = responseBody['data'];

        print("Failed to submit plan. Status: ${response.statusCode}");
        print("Error: ${response.body}");

        ToastHelper.showErrorToast(context, 'Failed To Save');
      }
    } catch (e) {
      print("🔥 Error submitting user: $e");
    } finally {
      if (mounted) {
        setState(() {
          isSubmitLoading = false; // 🔥 STOP LOADER
        });
      }
    }
  }

  // ================= UI =================

  @override
  Widget build(BuildContext context) {
    // Ensure global AppHeader remains visible by pushing content down by 64px
    return SafeArea(
      child: Scaffold(
        backgroundColor: Color(0xffD9EBE8),
        // ⭐ FIXED BUTTON FOOTER
        bottomNavigationBar: Container(
          padding: const EdgeInsets.all(16),
          color: const Color(0xFFF7FBFA),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end, // 👉 move button to right
            children: [],
          ),
        ),
        body: Container(
          // margin: const EdgeInsets.only(top: 64), // <-- keeps popup under global AppHeader
          width: double.infinity,
          // height: MediaQuery.of(context).size.height - 64,
          color: const Color(0xFFF7FBFA),
          child: Column(
            children: [
              // In-body header
              Container(
                height: 56,
                color: Color(0xFFE3F9F8),
                padding: const EdgeInsets.symmetric(horizontal: 12),
                child: Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.file_open),
                      onPressed: () => context.pop(),
                    ),
                    const Expanded(
                      child: Text(
                        'Endorsement Review',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    // if (isLoading)
                    //   const SizedBox(
                    //     width: 12,
                    //     height: 12,
                    //     child: CircularProgressIndicator(strokeWidth: 2),
                    //   ),
                    const SizedBox(width: 8),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => context.pop(),
                    ),
                  ],
                ),
              ),

              // Body: left PDF preview + right grouped form
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    children: [
                      // LEFT - PDF placeholder
                      Expanded(
                        flex: 1,
                        child: Container(
                          margin: const EdgeInsets.only(right: 12),
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: Colors.grey.shade200),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              const Text(
                                'Original Endorsement Document',
                                style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Expanded(
                                child: PolicyPdfViewer(
                                  pdfUrl: pdfUrl,
                                ), // 👈 Use separate widget
                              ),
                            ],
                          ),
                        ),
                      ),
                      // RIGHT - Grouped Form
                      Expanded(
                        flex: 1,
                        child: Card(
                          elevation: 2,
                          color: Colors.white,
                          margin: EdgeInsets.zero,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            children: [
                              /// HEADER
                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 20,
                                  vertical: 18,
                                ),
                                decoration: BoxDecoration(
                                  gradient: const LinearGradient(
                                    begin: Alignment.topLeft, // 135deg effect
                                    end: Alignment.bottomRight,
                                    colors: [
                                      Color(0xFFF0FBFB), // #f0fbfb
                                      Color(0xFFFFFFFF), // #ffffff
                                    ],
                                    stops: [0.0, 0.6], // 0% → 60%
                                  ),
                                  borderRadius: const BorderRadius.only(
                                    topLeft: Radius.circular(20),
                                    topRight: Radius.circular(20),
                                  ),
                                  border: const Border(
                                    bottom: BorderSide(
                                      color: Color(0xFFe5e7eb),
                                      width: 1,
                                    ),
                                  ),
                                ),
                                child: Row(
                                  children: [
                                    // Container(
                                    //   padding: const EdgeInsets.all(10),
                                    //   decoration: BoxDecoration(
                                    //     color: const Color(0xFF00b5b5),
                                    //     borderRadius: BorderRadius.circular(10),
                                    //   ),
                                    //   child: Text('📝'),
                                    //   // const Icon(Icons.edit, color: Color(0xFF0F766E)),
                                    // ),
                                    const SizedBox(width: 12),
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: const [
                                        Text(
                                          "Edit Endorsement",
                                          style: TextStyle(
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        SizedBox(height: 4),
                                        // Text(
                                        //   "Create a new endorsement request for an active policy",
                                        //   style: TextStyle(fontSize: 11, color: Color(0xFF6b7280),fontWeight: FontWeight.w500),
                                        // ),
                                      ],
                                    ),
                                    const Spacer(),
                                    Container(
                                      width: 34,
                                      height: 34,
                                      // padding: const EdgeInsets.all(8),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(8),
                                        border: Border.all(
                                          color: Color(0xFFe5e7eb),
                                          style: BorderStyle.solid,
                                        ),
                                      ),
                                      child: InkWell(
                                        onTap: () => Navigator.pop(context),
                                        child: const Icon(Icons.close),
                                      ),
                                    ),
                                  ],
                                ),
                              ),

                              Expanded(
                                child: Form(
                                  key: _formKeyEndrosment,
                                  autovalidateMode:
                                      AutovalidateMode.disabled,
                                  child: SingleChildScrollView(
                                    padding: const EdgeInsets.all(20),
                                    child: Column(
                                      children: [
                                        Visibility(
                                          visible: !isExternal,
                                          maintainState: true,
                                          maintainAnimation: true,
                                          maintainSize: false,
                                          child: Column(
                                            children: [
                                              buildSectionTitle(
                                                "SEARCH POLICY",
                                              ),
                                              const SizedBox(height: 15),

                                              Row(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  /// 🔹 VEHICLE SEARCH
                                                  Expanded(
                                                    child: Column(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        buildSearchBox(
                                                          controller:
                                                              _vehicleSearchController,
                                                          hint:
                                                              "Search By Vehicle Number",
                                                          onChanged: (val) async {
                                                            if (val
                                                                .isNotEmpty) {
                                                              await getVehicleListSearchData(
                                                                val,
                                                              );
                                                            } else {
                                                              setState(
                                                                () =>
                                                                    filteredVehicleData
                                                                        .clear(),
                                                              );
                                                            }
                                                          },
                                                        ),

                                                        /// 🔹 Vehicle Results Dropdown
                                                        if (filteredVehicleData
                                                            .isNotEmpty)
                                                          Container(
                                                            margin:
                                                                const EdgeInsets.only(
                                                                  top: 6,
                                                                ),
                                                            height: 150,
                                                            decoration: BoxDecoration(
                                                              color:
                                                                  Colors.white,
                                                              border: Border.all(
                                                                color:
                                                                    const Color(
                                                                      0xFFE5E7EB,
                                                                    ),
                                                              ),
                                                              borderRadius:
                                                                  BorderRadius.circular(
                                                                    12,
                                                                  ),
                                                              boxShadow: [
                                                                BoxShadow(
                                                                  color: Colors
                                                                      .black
                                                                      .withOpacity(
                                                                        0.05,
                                                                      ),
                                                                  blurRadius: 6,
                                                                ),
                                                              ],
                                                            ),
                                                            child: ListView.builder(
                                                              padding:
                                                                  EdgeInsets
                                                                      .zero,
                                                              itemCount:
                                                                  filteredVehicleData
                                                                      .length,
                                                              itemBuilder: (context, index) {
                                                                final vehicle =
                                                                    filteredVehicleData[index];
                                                                return InkWell(
                                                                  onTap: () {
                                                                    setState(() {
                                                                      controllers['policyNum']
                                                                              ?.text =
                                                                          vehicle['policy_number'] ??
                                                                          '';
                                                                      _vehicleSearchController
                                                                              .text =
                                                                          vehicle['policy_number'] ??
                                                                          '';
                                                                      filteredVehicleData
                                                                          .clear();
                                                                    });
                                                                  },
                                                                  child: Padding(
                                                                    padding: const EdgeInsets.symmetric(
                                                                      vertical:
                                                                          8,
                                                                      horizontal:
                                                                          12,
                                                                    ),
                                                                    child: Text(
                                                                      vehicle['policy_number'] ??
                                                                          '-',
                                                                      style:
                                                                          _textStyle1,
                                                                      overflow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                    ),
                                                                  ),
                                                                );
                                                              },
                                                            ),
                                                          ),
                                                      ],
                                                    ),
                                                  ),

                                                  const SizedBox(width: 20),

                                                  /// 🔹 POLICY SEARCH
                                                  Expanded(
                                                    child: Column(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        buildSearchBox(
                                                          controller:
                                                              _policySearchController,
                                                          hint:
                                                              "Search By Policy Number",
                                                          onChanged: (val) async {
                                                            if (val
                                                                .isNotEmpty) {
                                                              await getPolicyListSearchData(
                                                                val,
                                                              );
                                                            } else {
                                                              setState(
                                                                () =>
                                                                    filteredPolicyData
                                                                        .clear(),
                                                              );
                                                            }
                                                          },
                                                        ),

                                                        /// 🔹 Policy Results Dropdown
                                                        if (filteredPolicyData
                                                            .isNotEmpty)
                                                          Container(
                                                            margin:
                                                                const EdgeInsets.only(
                                                                  top: 6,
                                                                ),
                                                            height: 150,
                                                            decoration: BoxDecoration(
                                                              color:
                                                                  Colors.white,
                                                              border: Border.all(
                                                                color:
                                                                    const Color(
                                                                      0xFFE5E7EB,
                                                                    ),
                                                              ),
                                                              borderRadius:
                                                                  BorderRadius.circular(
                                                                    12,
                                                                  ),
                                                              boxShadow: [
                                                                BoxShadow(
                                                                  color: Colors
                                                                      .black
                                                                      .withOpacity(
                                                                        0.05,
                                                                      ),
                                                                  blurRadius: 6,
                                                                ),
                                                              ],
                                                            ),
                                                            child: ListView.builder(
                                                              padding:
                                                                  EdgeInsets
                                                                      .zero,
                                                              itemCount:
                                                                  filteredPolicyData
                                                                      .length,
                                                              itemBuilder: (context, index) {
                                                                final policy =
                                                                    filteredPolicyData[index];
                                                                return InkWell(
                                                                  onTap: () {
                                                                    setState(() {
                                                                      controllers['policyNum']
                                                                              ?.text =
                                                                          policy['policy_number'] ??
                                                                          '';
                                                                      _policySearchController
                                                                              .text =
                                                                          policy['policy_number'] ??
                                                                          '';
                                                                      filteredPolicyData
                                                                          .clear();
                                                                    });
                                                                  },
                                                                  child: Padding(
                                                                    padding: const EdgeInsets.symmetric(
                                                                      vertical:
                                                                          8,
                                                                      horizontal:
                                                                          12,
                                                                    ),
                                                                    child: Text(
                                                                      policy['policy_number'] ??
                                                                          '-',
                                                                      style:
                                                                          _textStyle1,
                                                                      overflow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                    ),
                                                                  ),
                                                                );
                                                              },
                                                            ),
                                                          ),
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),

                                              const Divider(
                                                color: Color(0xFFe5e7eb),
                                                thickness: 1,
                                                height: 40,
                                              ),
                                            ],
                                          ),
                                        ),

                                        /// ENDORSEMENT DETAILS
                                        buildSectionTitle(
                                          "ENDORSEMENT DETAILS",
                                        ),
                                        const SizedBox(height: 20),

                                        Row(
                                          children: [
                                            Expanded(
                                              child: buildEndrosPolicyFrom(
                                                context,
                                              ),
                                            ),
                                            const SizedBox(width: 20),
                                            Expanded(
                                              child: buildEndrosType(context),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(height: 20),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: buildPolicyNumber(context),
                                            ),
                                            const SizedBox(width: 20),
                                            Expanded(
                                              child: buildEndorsementNoField(
                                                context,
                                              ),
                                            ),
                                          ],
                                        ),

                                        const SizedBox(height: 20),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: buildContactPersonField(
                                                context,
                                              ),
                                            ),
                                            const SizedBox(width: 20),
                                            Spacer(),
                                            // Expanded(child: buildPendingDaysField(context)),
                                          ],
                                        ),

                                        Divider(
                                          color: Color(0xFFe5e7eb),
                                          thickness: 1,
                                          height: 40,
                                        ),

                                        if (isExternal) ...[
                                          buildSectionTitle(
                                            "POLICY INFORMATION",
                                          ),
                                          const SizedBox(height: 20),
                                          Row(
                                            children: [
                                              Expanded(
                                                child: buildRegNoField(context),
                                              ),
                                              const SizedBox(width: 20),
                                              Expanded(
                                                child: buildBrokerDropdown(
                                                  context,
                                                ),
                                              ),
                                              // Expanded(child: buildPendingDaysField(context)),
                                            ],
                                          ),
                                          const SizedBox(height: 25),
                                          Row(
                                            children: [
                                              Expanded(
                                                child: buildPolicyStartDate(
                                                  context,
                                                ),
                                              ),
                                              SizedBox(width: 20),
                                              Expanded(
                                                child: buildPolicyEndDate(
                                                  context,
                                                ),
                                              ),
                                            ],
                                          ),
                                          const SizedBox(height: 25),
                                          Row(
                                            children: [
                                              Expanded(
                                                child: buildInsurerDropdown(
                                                  context,
                                                ),
                                              ),
                                              const SizedBox(width: 20),
                                              Expanded(
                                                child: buildInsuredNameField(
                                                  context,
                                                ),
                                              ),
                                            ],
                                          ),

                                          Divider(
                                            color: Color(0xFFe5e7eb),
                                            thickness: 1,
                                            height: 40,
                                          ),
                                        ],

                                        /// UPLOAD & REMARKS
                                        buildSectionTitle("UPLOAD & REMARKS"),
                                        const SizedBox(height: 20),

                                        Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Expanded(child: buildUploadBox()),
                                            const SizedBox(width: 25),
                                            Expanded(
                                              child: buildEndrosRemarks(
                                                context,
                                              ),
                                            ),
                                          ],
                                        ),

                                        Divider(
                                          color: Color(0xFFe5e7eb),
                                          thickness: 1,
                                          height: 40,
                                        ),

                                        /// Financial & Status
                                        buildSectionTitle("Financial & Status"),
                                        const SizedBox(height: 20),

                                        /// FINANCIAL
                                        Row(
                                          children: [
                                            Expanded(
                                              child: buildFinancialToggle(),
                                            ),
                                            const SizedBox(width: 20),
                                            Expanded(
                                              child: showFinancialFields
                                                  ? buildPaymentModeDropdown()
                                                  : const Spacer(), // 👈 match dropdown total height
                                            ),
                                          ],
                                        ),

                                        if (showFinancialFields) ...[
                                          const SizedBox(height: 20),
                                          Row(
                                            children: [
                                              Expanded(
                                                child: buildPremiumField(
                                                  context,
                                                ),
                                              ),
                                              const SizedBox(width: 20),
                                              Expanded(
                                                child: buildCommissionField(
                                                  context,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],

                                        const SizedBox(height: 20),

                                        Row(
                                          children: [
                                            Expanded(
                                              child: buildLifecycleStatus(),
                                            ),
                                            const SizedBox(width: 25),
                                            Spacer(),
                                            // Expanded(child: buildVerificationStatus()),
                                          ],
                                        ),

                                        /// SAVE BUTTON
                                        // Align(
                                        //   alignment: Alignment.centerRight,
                                        //   child: ElevatedButton(
                                        //     style: ElevatedButton.styleFrom(
                                        //       backgroundColor: const Color(0xFF0F766E),
                                        //       padding: const EdgeInsets.symmetric(
                                        //         horizontal: 40,
                                        //         vertical: 14,
                                        //       ),
                                        //       shape: RoundedRectangleBorder(
                                        //         borderRadius: BorderRadius.circular(25),
                                        //       ),
                                        //     ),
                                        //     onPressed: () {
                                        //       if (!_formKeyEndrosment.currentState!.validate()) return;
                                        //       final dataSet = endrosmentDetails();
                                        //       createUserData(dataSet);
                                        //     },
                                        //     child: const Text(
                                        //       "Save Endorsement",
                                        //       style: TextStyle(fontSize: 13),
                                        //     ),
                                        //   ),
                                        // ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),

                              SizedBox(height: 20),

                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 24,
                                  vertical: 18,
                                ),
                                decoration: const BoxDecoration(
                                  border: Border(
                                    top: BorderSide(color: Color(0xFFE5E7EB)),
                                  ),
                                ),
                                child: Row(
                                  children: [
                                    /// Left Side - Required text
                                    const Text(
                                      "* Required fields",
                                      style: TextStyle(
                                        fontSize: 11,
                                        color: Color(0xFF6B7280),
                                      ),
                                    ),

                                    const Spacer(),

                                    /// Cancel Button
                                    Container(
                                      height: 44,
                                      margin: const EdgeInsets.only(right: 14),
                                      child: OutlinedButton(
                                        onPressed: () => Navigator.pop(context),
                                        style: OutlinedButton.styleFrom(
                                          backgroundColor: Colors.white,
                                          side: const BorderSide(
                                            color: Color(0xFFE5E7EB),
                                          ),
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                              12,
                                            ),
                                          ),
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 24,
                                          ),
                                        ),
                                        child: const Text(
                                          "Cancel",
                                          style: TextStyle(
                                            fontSize: 13,
                                            color: Color(0xFF374151),
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                    ),

                                    /// Save Button
                                    ValueListenableBuilder<TextEditingValue>(
                                      valueListenable: commissionController,
                                      builder: (context, value, _) {
                                        final bool isVerifiedAllowed =
                                            widget
                                                .item?['is_data_accuracy_checked']
                                                ?.toString() ==
                                            '0';

                                        final bool hasCommission = value.text
                                            .trim()
                                            .isNotEmpty;

                                        final bool isEnabled =
                                            isVerifiedAllowed && hasCommission;

                                        return Container(
                                          height: 44,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              12,
                                            ),

                                            /// 🔥 Dynamic Gradient
                                            gradient: isEnabled
                                                ? const LinearGradient(
                                                    colors: [
                                                      Color(0xFF14B8A6),
                                                      Color(0xFF0F766E),
                                                    ],
                                                  )
                                                : const LinearGradient(
                                                    colors: [
                                                      Color(0xFFE5E7EB),
                                                      Color(0xFFD1D5DB),
                                                    ],
                                                  ),

                                            boxShadow: isEnabled
                                                ? [
                                                    BoxShadow(
                                                      color: const Color(
                                                        0xFF0F766E,
                                                      ).withOpacity(0.25),
                                                      blurRadius: 8,
                                                      offset: const Offset(
                                                        0,
                                                        4,
                                                      ),
                                                    ),
                                                  ]
                                                : [],
                                          ),

                                          child: ElevatedButton(
                                            onPressed: (!isVerifiedAllowed || isSubmitLoading)
                                                ? null
                                                : () {
                                              if (!_formKeyEndrosment.currentState!.validate()) return;

                                              if (showFinancialFields && !hasCommission) {
                                                ToastHelper.showErrorToast(
                                                  context,
                                                  "Please enter Commission Amount",
                                                );
                                                return;
                                              }

                                              final dataSet = endrosmentDetails();
                                              createUserData(dataSet);
                                            },

                                            style: ElevatedButton.styleFrom(
                                              backgroundColor:
                                                  Colors.transparent,
                                              shadowColor: Colors.transparent,
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                    horizontal: 26,
                                                  ),
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(12),
                                              ),
                                            ),

                                            child: isSubmitLoading
                                                ? const SizedBox(
                                                    height: 18,
                                                    width: 18,
                                                    child:
                                                        CircularProgressIndicator(
                                                          strokeWidth: 2,
                                                          color: Colors.white,
                                                        ),
                                                  )
                                                : Row(
                                                    mainAxisSize:
                                                        MainAxisSize.min,
                                                    children: [
                                                      const Icon(
                                                        Icons.save,
                                                        size: 18,
                                                      ),
                                                      const SizedBox(width: 8),
                                                      Text(
                                                        roleId == 'Accounts'
                                                            ? 'Confirm Data Accuracy'
                                                            : 'Update Endorsement',
                                                        style: TextStyle(
                                                          fontSize: 13,
                                                          fontWeight:
                                                              FontWeight.w500,
                                                          color: isEnabled
                                                              ? Colors.white
                                                              : const Color(
                                                                  0xFF6B7280,
                                                                ),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                          ),
                                        );
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget stepCircle(int number, bool completed, bool active) {
    if (completed) {
      return Container(
        width: 28,
        height: 28,
        decoration: const BoxDecoration(
          color: Color(0xFF16A34A),
          shape: BoxShape.circle,
        ),
        child: const Icon(Icons.check, size: 16, color: Colors.white),
      );
    }

    if (active) {
      return Container(
        width: 32,
        height: 32,
        decoration: const BoxDecoration(
          color: Color(0xFFd4edef), // outer grey ring
          shape: BoxShape.circle,
        ),
        child: Center(
          child: Container(
            width: 26,
            height: 26,
            decoration: const BoxDecoration(
              color: Color(0xFF00b5b5), // teal inner
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              number.toString(),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      );
    }

    return Container(
      width: 28,
      height: 28,
      decoration: const BoxDecoration(
        color: Color(0xFFE5E7EB),
        shape: BoxShape.circle,
      ),
      alignment: Alignment.center,
      child: Text(
        number.toString(),
        style: const TextStyle(
          color: Color(0xFF6B7280),
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget buildSearchBox({
    required TextEditingController controller,
    required String hint,
    required Function(String) onChanged,
  }) {
    final FocusNode focusNode = FocusNode();
    bool isFocused = false;

    return StatefulBuilder(
      builder: (context, setStateSB) {
        focusNode.addListener(() {
          setStateSB(() {
            isFocused = focusNode.hasFocus;
          });
        });

        return Container(
          height: 40,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
              color: isFocused
                  ? const Color(0xFF008f8f) // teal border
                  : const Color(0xFFE5E7EB),
              width: 1.5,
            ),
            boxShadow: isFocused
                ? [
                    BoxShadow(
                      color: const Color(0xFF008f8f).withOpacity(0.15),
                      blurRadius: 8,
                      spreadRadius: 1,
                    ),
                  ]
                : [],
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  focusNode: focusNode,
                  controller: controller,
                  onChanged: onChanged,
                  style: const TextStyle(
                    fontSize: 13,
                    color: Color(0xFF374151),
                  ),
                  decoration: InputDecoration(
                    hintText: hint,
                    hintStyle: const TextStyle(
                      color: Color(0xFF9CA3AF),
                      fontSize: 13,
                    ),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 14,
                      vertical: 15,
                    ),
                  ),
                ),
              ),

              /// Search Icon Button
              Container(
                margin: const EdgeInsets.only(right: 8),
                width: 30,
                height: 30,
                decoration: BoxDecoration(
                  color: const Color(0xFF008f8f),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.search, color: Colors.white, size: 18),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget buildUploadBox() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        /// Label Row
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: const [
            Text(
              "Upload Document",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: Color(0xFF374151),
              ),
            ),
            Text(
              "PDF / JPG / PNG",
              style: TextStyle(fontSize: 10, color: Color(0xFF6B7280)),
            ),
          ],
        ),
        const SizedBox(height: 10),

        /// 🔹 IF EXISTING FILE (EDIT MODE)
        if (showExistingFile && existingFileName != null)
          Container(
            height: 70,
            padding: const EdgeInsets.symmetric(horizontal: 14),
            decoration: BoxDecoration(
              color: const Color(0xFFF8FAFC),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: const Color(0xFF0F766E), width: 1.5),
            ),
            child: Row(
              children: [
                const Icon(Icons.insert_drive_file, color: Color(0xFF0F766E)),

                const SizedBox(width: 12),

                Expanded(
                  child: Text(
                    existingFileName!,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),

                /// ❌ REMOVE BUTTON
                GestureDetector(
                  onTap: () {
                    setState(() {
                      showExistingFile = false;
                      existingFileName = null;
                      docUploadedEndorsFile = null;
                    });
                  },
                  child: const Icon(Icons.close, color: Colors.red),
                ),
              ],
            ),
          )
        /// 🔹 ELSE SHOW UPLOAD BOX
        else
          GestureDetector(
            onTap: () async {
              FilePickerResult? result = await FilePicker.platform.pickFiles(
                type: FileType.custom,
                allowedExtensions: ['pdf', 'jpg', 'jpeg', 'png'],
              );

              if (result != null) {
                setState(() {
                  docUploadedEndorsFile = result.files.first;
                });
              }
            },
            child: Container(
              height: 160,
              decoration: BoxDecoration(
                color: const Color(0xFFF8FAFC),
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: const Color(0xFF0F766E), width: 1.5),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.attach_file,
                    size: 34,
                    color: Color(0xFF9CA3AF),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    docUploadedEndorsFile != null
                        ? docUploadedEndorsFile!.name
                        : "Click to upload or drag & drop",
                    style: const TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w400,
                      color: Color(0xFF374151),
                    ),
                  ),
                  const SizedBox(height: 6),
                  const Text(
                    "Endorsement document, policy copy",
                    style: TextStyle(fontSize: 11, color: Color(0xFF6B7280)),
                  ),
                  const SizedBox(height: 10),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      buildFileChip("PDF"),
                      const SizedBox(width: 8),
                      buildFileChip("JPG"),
                      const SizedBox(width: 8),
                      buildFileChip("PNG"),
                      const SizedBox(width: 8),
                      buildFileChip("Max 5MB"),
                    ],
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }

  // Widget buildUploadBox() {
  //   return Column(
  //     crossAxisAlignment: CrossAxisAlignment.start,
  //     children: [
  //       /// Label Row
  //       Row(
  //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //         children: const [
  //           Text(
  //             "Upload Document",
  //             style: TextStyle(
  //               fontSize: 12,
  //               fontWeight: FontWeight.w500,
  //               color: Color(0xFF374151),
  //             ),
  //           ),
  //           Text(
  //             "PDF / JPG / PNG",
  //             style: TextStyle(
  //               fontSize: 10,
  //               color: Color(0xFF6B7280),
  //             ),
  //           ),
  //         ],
  //       ),
  //       const SizedBox(height: 10),
  //
  //       /// Upload Container
  //       GestureDetector(
  //         onTap: () async {
  //           FilePickerResult? result =
  //           await FilePicker.platform.pickFiles();
  //
  //           if (result != null) {
  //             setState(() {
  //               docUploadedEndorsFile =
  //                   result.files.first;
  //             });
  //           }
  //         },
  //         child: Container(
  //           height: 160,
  //           decoration: BoxDecoration(
  //             color: const Color(0xFFF8FAFC),
  //             borderRadius: BorderRadius.circular(14),
  //             border: Border.all(
  //               color: const Color(0xFF0F766E),
  //               width: 1.5,
  //               style: BorderStyle.solid,
  //             ),
  //           ),
  //           child: Column(
  //             mainAxisAlignment: MainAxisAlignment.center,
  //             children: [
  //               const Icon(
  //                 Icons.attach_file,
  //                 size: 34,
  //                 color: Color(0xFF9CA3AF),
  //               ),
  //               const SizedBox(height: 12),
  //               Text(
  //                 docUploadedEndorsFile != null
  //                     ? docUploadedEndorsFile!.name
  //                     : "Click to upload or drag & drop",
  //                 style: const TextStyle(
  //                   fontSize: 13,
  //                   fontWeight: FontWeight.w400,
  //                   color: Color(0xFF374151),
  //                 ),
  //               ),
  //               const SizedBox(height: 6),
  //               const Text(
  //                 "Endorsement document, policy copy",
  //                 style: TextStyle(
  //                   fontSize: 11,
  //                   color: Color(0xFF6B7280),
  //                 ),
  //               ),
  //               const SizedBox(height: 10),
  //
  //               /// File Type Chips
  //               Row(
  //                 mainAxisAlignment: MainAxisAlignment.center,
  //                 children: [
  //                   buildFileChip("PDF"),
  //                   const SizedBox(width: 8),
  //                   buildFileChip("JPG"),
  //                   const SizedBox(width: 8),
  //                   buildFileChip("PNG"),
  //                   const SizedBox(width: 8),
  //                   buildFileChip("Max 5MB"),
  //                 ],
  //               )
  //             ],
  //           ),
  //         ),
  //       ),
  //     ],
  //   );
  // }

  Widget buildFileChip(String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: const Color(0xFFE5E7EB),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        text,
        style: const TextStyle(fontSize: 10, color: Color(0xFF374151)),
      ),
    );
  }

  Widget buildSectionTitle(String title) {
    return Row(
      children: [
        Container(width: 3, height: 14, color: Color(0xFF00b5b5)),
        const SizedBox(width: 8),
        Text(
          title,
          style: TextStyle(
            fontWeight: FontWeight.w700,
            fontSize: 10,
            letterSpacing: 2,
            color: Color(0xFF6b7280),
          ),
        ),
      ],
    );
  }

  Widget buildPolicyNumber(context) {
    return buildCommonTextField(
      label: "Policy Number",
      controller: controllers['policyNum']!,
      isRequired: true,
      readOnly: isInternal,
      isFocused: isPolicyNumberFocused,
      onFocusChanged: (val) {
        setState(() {
          isPolicyNumberFocused = val;
        });
      },
    );
  }

  //------------------------- Endrosment Part -----------------------------------

  Widget buildEndrosRemarks(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          "Remarks",
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: Color(0xFF374151),
          ),
        ),
        const SizedBox(height: 10),

        Container(
          height: 160, // 👈 textarea height
          decoration: BoxDecoration(
            color: const Color(0xFFF9FAFB),
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: const Color(0xFFE5E7EB)),
          ),
          child: TextFormField(
            controller: controllers['remarks'],
            keyboardType: TextInputType.multiline,
            maxLines: null, // allow unlimited lines
            textAlignVertical: TextAlignVertical.top,
            style: const TextStyle(fontSize: 13, color: Color(0xFF374151)),
            decoration: const InputDecoration(
              hintText:
                  "Describe the reason for this endorsement request, changes being made, or any additional instructions...",
              hintStyle: TextStyle(fontSize: 12, color: Color(0xFF9CA3AF)),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(16),
            ),
            // validator: (value) =>
            //     Validators.requiredField(value, "remarks"),
          ),
        ),
      ],
    );
  }

  Widget buildPolicyStartDate(context) {
    return buildDateField(
      context,
      "Policy Start Date",
      policyStartController,
      isStartDateFocused,
      (val) => setState(() => isStartDateFocused = val),
    );
  }

  Widget buildPolicyEndDate(context) {
    return buildDateField(
      context,
      "Policy End Date",
      policyEndController,
      isEndDateFocused,
      (val) => setState(() => isEndDateFocused = val),
    );
  }

  Widget buildDateField(
    BuildContext context,
    String label,
    TextEditingController controller,
    bool isFocused,
    Function(bool) onFocusChanged,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            text: '$label *',
            style: const TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w500,
              color: Color(0xFF374151),
            ),
            children: label.contains("*")
                ? const [
                    TextSpan(
                      text: " *",
                      style: TextStyle(color: Colors.red),
                    ),
                  ]
                : [],
          ),
        ),
        const SizedBox(height: 8),

        AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          constraints: const BoxConstraints(minHeight: 40),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(14)),
          child: GestureDetector(
            onTap: () async {
              onFocusChanged(true);

              DateTime? picked = await showDatePicker(
                context: context,
                firstDate: DateTime(2000),
                lastDate: DateTime.now(),
                initialDate: DateTime.now(),
              );

              onFocusChanged(false);

              if (picked != null) {
                controller.text =
                    "${picked.day.toString().padLeft(2, '0')}-"
                    "${picked.month.toString().padLeft(2, '0')}-"
                    "${picked.year}";
              }
            },
            child: AbsorbPointer(
              child: TextFormField(
                controller: controller,
                validator: (value) {
                  if (isExternal && (value == null || value.isEmpty)) {
                    return "$label is required";
                  }
                  return null;
                },
                readOnly: true,
                style: const TextStyle(fontSize: 13, color: Color(0xFF374151)),
                decoration: InputDecoration(
                  filled: true,
                  fillColor: const Color(0xFFF9FAFB),

                  isDense: true, // ⭐ important
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 13,
                  ),

                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(14),
                    borderSide: const BorderSide(
                      color: Color(0xFFE5E7EB),
                      width: 1.5,
                    ),
                  ),

                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(14),
                    borderSide: const BorderSide(
                      color: Color(0xFF0F766E),
                      width: 1.5,
                    ),
                  ),

                  errorBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(14),
                    borderSide: const BorderSide(color: Colors.red, width: 1.5),
                  ),

                  focusedErrorBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(14),
                    borderSide: const BorderSide(color: Colors.red, width: 1.5),
                  ),

                  helperText: " ",
                  helperStyle: const TextStyle(height: 0.8),

                  errorStyle: const TextStyle(fontSize: 11, height: 1.3),

                  suffixIcon: const Icon(
                    Icons.calendar_today_outlined,
                    size: 18,
                    color: Color(0xFF6B7280),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildRegNoField(context) {
    return buildCommonTextField(
      label: "Vehicle Number",
      controller: regNoController,
      isRequired: isExternal,
      isFocused: isRegNoFocused,
      onFocusChanged: (val) {
        setState(() => isRegNoFocused = val);
      },
    );
  }

  Widget buildInsuredNameField(context) {
    return buildCommonTextField(
      label: "Insured Name",
      controller: insuredNameController,
      isRequired: isExternal,
      isFocused: isInsuredNameFocused,
      onFocusChanged: (val) {
        setState(() => isInsuredNameFocused = val);
      },
    );
  }

  Widget buildEndorsementNoField(context) {
    return buildCommonTextField(
      label: "Endorsement No",
      controller: endorsementNoController,
      isRequired: false,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
      ],
      isFocused: isEndorsementNoFocused,
      onFocusChanged: (val) {
        setState(() => isEndorsementNoFocused = val);
      },
    );
  }

  Widget buildContactPersonField(context) {
    return buildCommonTextField(
      label: "Contact Person",
      controller: contactPersonController,
      isRequired: false,
      isFocused: isContactPersonFocused,
      onFocusChanged: (val) {
        setState(() => isContactPersonFocused = val);
      },
    );
  }

  // Widget buildPendingDaysField(context) {
  //   return buildCommonTextField(
  //     label: "Pending Days",
  //     controller: pendingDaysController,
  //     isRequired: isInternal,
  //     keyboardType: TextInputType.number,
  //     isFocused: isPendingDaysFocused,
  //     onFocusChanged: (val) {
  //       setState(() => isPendingDaysFocused = val);
  //     },
  //   );
  // }

  Widget buildPremiumField(context) {
    return buildCommonTextField(
      label: "Endorsement Premium",
      controller: premiumController,
      isRequired: showFinancialFields,
      keyboardType: TextInputType.number,
      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      isFocused: isPremiumFocused,
      onFocusChanged: (val) {
        setState(() => isPremiumFocused = val);
      },
    );
  }

  Widget buildCommissionField(context) {
    return buildCommonTextField(
      label: "Commission Amount",
      controller: commissionController,
      isRequired: showFinancialFields,
      keyboardType: TextInputType.number,
      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      isFocused: isCommissionFocused,
      onFocusChanged: (val) {
        setState(() => isCommissionFocused = val);
      },
    );
  }

  Widget buildCommonTextField({
    required String label,
    required TextEditingController controller,
    required bool isRequired,
    bool readOnly = false,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
    required bool isFocused,
    required Function(bool) onFocusChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            text: label,
            style: const TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w500,
              color: Color(0xFF374151),
            ),
            children: isRequired
                ? const [
                    TextSpan(
                      text: " *",
                      style: TextStyle(color: Colors.red),
                    ),
                  ]
                : [],
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          readOnly: readOnly,
          keyboardType: keyboardType,
          inputFormatters: inputFormatters,
          validator: (value) {
            if (isRequired && (value == null || value.trim().isEmpty)) {
              return "$label is required";
            }
            return null;
          },
          style: const TextStyle(fontSize: 13, color: Color(0xFF374151)),
          decoration: InputDecoration(
            filled: true,
            fillColor: const Color(0xFFF9FAFB),

            isDense: true, // ⭐ important
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 13,
            ),

            helperText: " ", // 🔥 IMPORTANT FIX
            helperStyle: const TextStyle(height: 0.8),

            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(
                color: Color(0xFFE5E7EB),
                width: 1.5,
              ),
            ),

            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(
                color: Color(0xFF0F766E),
                width: 1.5,
              ),
            ),

            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(color: Colors.red, width: 1.5),
            ),

            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: const BorderSide(color: Colors.red, width: 1.5),
            ),

            errorStyle: const TextStyle(fontSize: 11, height: 1.3),
          ),
        ),
        // AnimatedContainer(
        //   duration: const Duration(milliseconds: 180),
        //   constraints: const BoxConstraints(
        //     minHeight: 40,
        //   ),
        //   decoration: BoxDecoration(
        //     color: isFocused ? Colors.white : const Color(0xFFF9FAFB),
        //     borderRadius: BorderRadius.circular(14),
        //     border: Border.all(
        //       color: isFocused
        //           ? const Color(0xFF0F766E)
        //           : const Color(0xFFE5E7EB),
        //       width: 1.5,
        //     ),
        //     boxShadow: isFocused
        //         ? [
        //       BoxShadow(
        //         color: Color(0xFF0F766E).withOpacity(0.12),
        //         blurRadius: 6,
        //         spreadRadius: 1,
        //       )
        //     ]
        //         : [],
        //   ),
        //   child: Focus(
        //     onFocusChange: onFocusChanged,
        //     child: TextFormField(
        //       controller: controller,
        //       readOnly: readOnly,
        //       validator: (value) {
        //         if (isRequired) {
        //           if (value == null || value.trim().isEmpty) {
        //             return "$label is required";
        //           }
        //         }
        //         return null;
        //       },
        //       keyboardType: keyboardType,
        //       style: const TextStyle(
        //         fontSize: 13,
        //         color: Color(0xFF374151),
        //       ),
        //       decoration: const InputDecoration(
        //         border: InputBorder.none,
        //         isDense: true,
        //         contentPadding: const EdgeInsets.symmetric(
        //           horizontal: 16,
        //           vertical: 10,
        //         ),
        //       ),
        //     ),
        //   ),
        // ),
      ],
    );
  }

  Widget buildFinancialToggle() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "Financial Status",
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: Color(0xFF374151),
              ),
            ),
            const Text(" *", style: TextStyle(color: Colors.red)),
            const SizedBox(width: 12),

            /// 👇 IMPORTANT PART
            Expanded(
              child: const Text(
                "Additional premium?",
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 11, color: Color(0xFF6B7280)),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),

        /// Segmented Container
        Container(
          height: 40,
          decoration: BoxDecoration(
            color: const Color(0xFFF3F4F6),
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: const Color(0xFFE5E7EB)),
          ),
          child: Row(
            children: [
              /// YES BUTTON
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      financialType = "Yes";
                      showFinancialFields = true;

                      // 🔥 Clear old values
                      premiumController.clear();
                      commissionController.clear();
                      selectedPaymentModeId = null;
                    });
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: financialType == "Yes"
                          ? const Color(0xFF16a34a)
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    alignment: Alignment.center,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.check,
                          size: 16,
                          color: financialType == "Yes"
                              ? const Color(0xFFFFFFFF)
                              : const Color(0xFF9CA3AF),
                        ),
                        const SizedBox(width: 6),
                        Text(
                          "Yes",
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                            color: financialType == "Yes"
                                ? const Color(0xFFFFFFFF)
                                : const Color(0xFF6B7280),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              /// Divider
              Container(width: 1, color: const Color(0xFFE5E7EB)),

              /// NO BUTTON
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      financialType = "No";
                      showFinancialFields = false;

                      // 🔥 Clear old values
                      premiumController.clear();
                      commissionController.clear();
                      selectedPaymentModeId = null;
                    });
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: financialType == "No"
                          ? const Color(0xFFE5E7EB)
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    alignment: Alignment.center,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.close,
                          size: 16,
                          color: financialType == "No"
                              ? const Color(0xFF374151)
                              : const Color(0xFF9CA3AF),
                        ),
                        const SizedBox(width: 6),
                        Text(
                          "No",
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                            color: financialType == "No"
                                ? const Color(0xFF374151)
                                : const Color(0xFF6B7280),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),

        /// ⭐ IMPORTANT: reserve space like TextFormField
        const SizedBox(height: 20),
      ],
    );
  }

  Widget buildSegmentedStatus({
    required String title,
    required List<Map<String, dynamic>> options,
    required String selectedValue,
    required Function(String) onChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: Color(0xFF374151),
              ),
            ),
            const Text(" *", style: TextStyle(color: Colors.red)),
          ],
        ),
        const SizedBox(height: 12),

        Row(
          children: options.map((option) {
            final bool isSelected = selectedValue == option["value"];

            return Expanded(
              child: GestureDetector(
                onTap: () => onChanged(option["value"]),
                child: Container(
                  height: 40,
                  margin: const EdgeInsets.only(right: 12),
                  decoration: BoxDecoration(
                    color: isSelected
                        ? option["selectedColor"]
                        : const Color(0xFFF3F4F6),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: isSelected
                          ? option["borderColor"] ?? option["selectedColor"]
                          : const Color(0xFFE5E7EB),
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        option["icon"],
                        size: 16,
                        color: isSelected
                            ? option["textColor"] ?? const Color(0xFF111827)
                            : const Color(0xFF6B7280),
                      ),
                      const SizedBox(width: 6),
                      Text(
                        option["label"],
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          color: isSelected
                              ? option["textColor"] ?? const Color(0xFF111827)
                              : const Color(0xFF6B7280),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget buildLifecycleStatus() {
    return buildSegmentedStatus(
      title: "Lifecycle Status",
      selectedValue: lifecycleStatus,
      options: [
        {
          "label": "Open",
          "value": "Open",
          "icon": Icons.circle,
          "selectedColor": const Color(0xFFfef3c7), // 🔥 Yellow
          "textColor": const Color(0xFF92400E),
        },
        {
          "label": "Closed",
          "value": "Closed",
          "icon": Icons.circle,
          "selectedColor": const Color(0xFFdcfce7A), // Green light
          "textColor": const Color(0xFF065F46),
        },
      ],
      onChanged: (val) {
        setState(() {
          lifecycleStatus = val;
          print(lifecycleStatus);
        });
      },
    );
  }

  Widget buildVerificationStatus() {
    return buildSegmentedStatus(
      title: "Verification Status",
      selectedValue: verificationStatus,
      options: [
        {
          "label": "To Verify",
          "value": "To Verify",
          "icon": Icons.diamond,
          "selectedColor": const Color(0xFF93C5FD), // 🔥 Blue
          "textColor": const Color(0xFF1E40AF),
        },
        {
          "label": "Verified",
          "value": "Verified",
          "icon": Icons.check_box,
          "selectedColor": const Color(0xFFD1FAE5),
          "textColor": const Color(0xFF065F46),
        },
      ],
      onChanged: (val) {
        setState(() {
          verificationStatus = val;
        });
      },
    );
  }

  Widget buildCommonDropdown({
    required String label,
    required String hintText,
    required List<Map<String, dynamic>> items,
    required Map<String, dynamic>? selectedItem,
    required String Function(Map<String, dynamic>) itemAsString,
    required Function(Map<String, dynamic>?) onChanged,
    required bool isRequired,
    required bool isFocused,
    required Function(bool) onFocusChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            text: label,
            style: const TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w500,
              color: Color(0xFF374151),
            ),
            children: isRequired
                ? const [
                    TextSpan(
                      text: " *",
                      style: TextStyle(color: Colors.red),
                    ),
                  ]
                : [],
          ),
        ),
        const SizedBox(height: 8),

        Container(
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(14)),
          child: DropdownSearch<Map<String, dynamic>>(
            selectedItem: selectedItem,
            items: (f, i) => items,
            itemAsString: itemAsString,
            compareFn: (item, s) => item['id'].toString() == s['id'].toString(),
            onChanged: onChanged,

            validator: (value) {
              if (isRequired && value == null) {
                return "$label is required";
              }
              return null;
            },

            onBeforePopupOpening: (val) async {
              onFocusChanged(true);
              return true;
            },

            popupProps: PopupProps.menu(
              onDismissed: () {
                onFocusChanged(false);
              },
              showSearchBox: true,
            ),

            decoratorProps: DropDownDecoratorProps(
              decoration: InputDecoration(
                filled: true,
                fillColor: const Color(0xFFF9FAFB),

                isDense: true, // ⭐ important
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 13,
                ),

                helperText: " ", // 🔥 IMPORTANT FIX
                helperStyle: const TextStyle(height: 0.8),

                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(
                    color: Color(0xFFE5E7EB),
                    width: 1.5,
                  ),
                ),

                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(
                    color: Color(0xFF0F766E),
                    width: 1.5,
                  ),
                ),

                errorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: Colors.red, width: 1.5),
                ),

                focusedErrorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: Colors.red, width: 1.5),
                ),

                errorStyle: const TextStyle(fontSize: 11, height: 1.3),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildEndrosType(context) {
    Map<String, dynamic>? selectedItem = filteredEndrosmentData.firstWhere(
      (item) => item['id'].toString() == selectedEndorsement,
      orElse: () => {},
    );

    return buildCommonDropdown(
      label: "Endorsement Type",
      hintText: "Select Endorsement Type",
      isRequired: true,
      items: filteredEndrosmentData,
      selectedItem: selectedItem.isNotEmpty ? selectedItem : null,
      isFocused: isEndorsementTypeFocused,
      onFocusChanged: (val) {
        setState(() {
          isEndorsementTypeFocused = val;
        });
      },
      itemAsString: (val) => val['endorsement_type'].toString(),
      onChanged: (val) {
        if (val != null) {
          setState(() {
            selectedEndorsement = val['id'];
          });
        }
      },
    );
  }

  Widget buildEndrosPolicyFrom(context) {
    Map<String, dynamic>? selectedItem =
        policyFromOptions
            .where(
              (item) => item['policy_from'] == selectedEndrosementPolicyFrom,
            )
            .isNotEmpty
        ? policyFromOptions.firstWhere(
            (item) => item['policy_from'] == selectedEndrosementPolicyFrom,
          )
        : null;

    return buildCommonDropdown(
      label: "Policy From",
      hintText: "Select Policy From",
      isRequired: true,
      items: policyFromOptions,
      selectedItem: selectedItem,
      itemAsString: (val) => val['policy_from'],
      isFocused: isPolicyFromFocused,
      onFocusChanged: (val) {
        setState(() {
          isPolicyFromFocused = val;
        });
      },
      onChanged: (val) {
        if (val != null) {
          setState(() {
            selectedEndrosementPolicyFrom = val['policy_from'];

            isInternal = selectedEndrosementPolicyFrom == "Internal";
            isExternal = selectedEndrosementPolicyFrom == "External";

            /// 🔥 POLICY NUMBER LOGIC
            if (isExternal) {
              controllers['policyNum']!.clear();
              _vehicleSearchController.clear();
              _policySearchController.clear();
              filteredVehicleData.clear();
              filteredPolicyData.clear();
              isPolicyNumberReadOnly = false;
              controllers['policyNum']!.clear();
            } else {
              isPolicyNumberReadOnly = true;
            }

            // 🔥 CLEAR FIELDS WHEN SWITCHING
            if (isInternal) {
              selectedInsurer = null;
              selectedBroker = null;
              selectedPaymentModeId = null;

              insuredNameController.clear();
              regNoController.clear();
              policyStartController.clear();
              policyEndController.clear();
            }

            if (isExternal) {
              endorsementNoController.clear();
              contactPersonController.clear();
              // pendingDaysController.clear();
            }

            showFinancialFields = financialType == "Yes";
          });
        }
      },
    );
  }

  Widget buildInsurerDropdown(context) {
    Map<String, dynamic>? selectedItem =
        insurerList
            .where(
              (item) => item['id']?.toString() == selectedInsurer?.toString(),
            )
            .isNotEmpty
        ? insurerList.firstWhere(
            (item) => item['id']?.toString() == selectedInsurer?.toString(),
          )
        : null;

    return buildCommonDropdown(
      label: "Insurer",
      hintText: "Select Insurer",
      isRequired: isExternal,
      items: insurerList,
      selectedItem: selectedItem,
      itemAsString: (val) => val['short_name'] ?? val['name'] ?? "",
      isFocused: isInsurerFocused,
      onFocusChanged: (val) {
        setState(() => isInsurerFocused = val);
      },
      onChanged: (val) {
        if (val != null) {
          setState(() {
            selectedInsurer = val['id'];
          });
        }
      },
    );
  }

  Widget buildBrokerDropdown(context) {
    Map<String, dynamic>? selectedItem =
        brokerList
            .where(
              (item) => item['id']?.toString() == selectedBroker?.toString(),
            )
            .isNotEmpty
        ? brokerList.firstWhere(
            (item) => item['id']?.toString() == selectedBroker?.toString(),
          )
        : null;

    return buildCommonDropdown(
      label: "Broker",
      hintText: "Select Broker",
      isRequired: isExternal,
      items: brokerList,
      selectedItem: selectedItem,
      itemAsString: (val) => val['short_name'] ?? val['name'] ?? "",
      isFocused: isBrokerFocused,
      onFocusChanged: (val) {
        setState(() => isBrokerFocused = val);
      },
      onChanged: (val) {
        if (val != null) {
          setState(() {
            selectedBroker = val['id'];
          });
        }
      },
    );
  }

  Widget buildPaymentModeDropdown() {
    Map<String, dynamic>? selectedItem =
        getPaymentModeData
            .where(
              (item) =>
                  item['id']?.toString() == selectedPaymentModeId?.toString(),
            )
            .isNotEmpty
        ? getPaymentModeData.firstWhere(
            (item) =>
                item['id']?.toString() == selectedPaymentModeId?.toString(),
          )
        : null;

    return buildCommonDropdown(
      label: "Payment Mode",
      hintText: "Select Payment Mode",
      isRequired: true,
      items: getPaymentModeData,
      selectedItem: selectedItem,

      /// 🔥 IMPORTANT FIX HERE
      itemAsString: (val) => val['value'] ?? "",

      isFocused: isPaymentModeFocused,
      onFocusChanged: (val) {
        setState(() => isPaymentModeFocused = val);
      },
      onChanged: (val) {
        if (val != null) {
          setState(() {
            selectedPaymentModeId = val['id'].toString();
          });
        }
      },
    );
  }
  // ------------------- STyle ---------------------------------

  static final TextStyle _textStyle = TextStyle(
    fontSize: 11,
    fontWeight: FontWeight.w400,
  );
  static final TextStyle _textStyle1 = TextStyle(
    fontSize: 9,
    fontWeight: FontWeight.w300,
  );
}
