import 'dart:async';
import 'dart:convert';

import 'package:dropdown_search/dropdown_search.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:nhance_partner/data/utils/toastNotification.dart';

import 'package:shared_preferences/shared_preferences.dart';

import '../../../../../core/config/env.dart';
import '../../../../../core/routing/routes.dart';
import '../../../../../core/services/api_service.dart';
import '../../../../../data/services/auth_service.dart';
import '../../../../../data/utils/validators.dart';
import '../../../../layouts/responsive_layout.dart';
import '../../../../providers/manager_provider.dart';
import '../../../../providers/quotation_staff_proivder.dart';
import '../../../../providers/userRoleProvider.dart';
import '../../../../themes/indicators/customizd_file_upload.dart';
import '../../../../themes/indicators/input_field_decoration.dart';
import '../../../../themes/indicators/text_field_theme.dart';
import '../../../../themes/indicators/text_field_theme_inline_editor.dart'
    hide UpperCaseTextFormatter;

class CreateProposal_Quick extends ConsumerStatefulWidget {
  const CreateProposal_Quick({super.key});

  @override
  ConsumerState<CreateProposal_Quick> createState() =>
      CreateProposal_QuickFormState();
}

class CreateProposal_QuickFormState
    extends ConsumerState<CreateProposal_Quick> {
  late ApiService apiService;
  String? _token;

  String? selectedFileNames;

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

  bool isLoading = false;
  bool _autoValidate = false;
  late TextEditingController controller;
  Map<String, TextEditingController> controllers = {};

  final _formKey = GlobalKey<FormState>();
  Map<String, String?> fieldErrors = {};
  String? docUploadedFileUrlFromApi;
  String? selectedId;
  PlatformFile? docUploadedFile;

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

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

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

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

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

  List<String> tabHeader = ['idv', 'premium_Amount', 'insurer', 'regNo'];

  late FocusNode partnerFocusNode;

  List<QuotationRow> rows = [];

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

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

  List<Map<String, dynamic>> getInsuranceTypeData = [];
  List<Map<String, dynamic>> filteredInsuranceData = [];

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

  List<Map<String, dynamic>> getCreatedProposalData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredCreatedProposalData = [];

  String? selectedAgent;
  String? selectedInsPlanType;
  String? selectedEndorsement;
  String? selectedPaymentMode;

  dynamic roleId;
  dynamic userId;
  dynamic managerId;

  bool isSingleSave = false;
  bool _isResetting = false;

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

  Map<String, dynamic> quotationData() {
    final data = {
      "insurer_id": selectedInsurer,
      "premium_amount": controllers["premium_Amount"]?.text,
      "insurance_plan_type_id": selectedInsPlanType,
    };
    return data;
  }

  Map<String, dynamic> dataDetails() {
    print('checking agent id $selectedAgent');

    final data = {
      "agent_id":
          ((roleId == 'handler') ||
              (roleId == 'manager') ||
              (roleId == 'staff'))
          ? selectedAgent
          : userId,
      "name": controllers["name"]?.text,
      "mobile": controllers["mobile"]?.text,
      "email": controllers["email"]?.text,
      "reg_no": controllers["regNo"]?.text,

      // "vehicle_type_id": selectedVehicleType,
      "is_quick_quote": "1",
      // "quotation": quotationList,
      "quotation": jsonEncode(quotationList),
      // "is_data_created_by_handler": roleId == 'handler' ? '1' : '0',
      // "is_data_created_by_manager": roleId == 'manager' ? '1' : '0',
      "is_data_created_by_staff": roleId != null ? '1' : '0',
      // "insurer_id": selectedInsurer,
      // "rc_file_name": "rc_doc.pdf",
      // "id_proof_file_name": "id_proof.pdf",
      // "previous_policy_file_name": "previous_policy.pdf",
      "remarks": controllers["remarks"]?.text,
      // "assigned_to": (roleId == 'staff') ? userId : selectedStaff,
      "assigned_to": userId,
      "insurer_id": selectedInsurer,
      "broker_id": selectedBroker,
      "manager_id": managerId,
      "created_by": userId,
    };

    return data;
  }

  @override
  void initState() {
    super.initState();
    apiService = ApiService();
    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }
    partnerFocusNode = FocusNode();

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

      final prefs = await SharedPreferences.getInstance();

      if (managerId != null) {
        print('managerId - $managerId');
        getAgentList(managerId);
        getQuickQuotationList(managerId);
      }
    });
    // 🔹 Init logic here (API calls, token fetch, etc.)
    _initializeToken();
    getInsuranceType();
    getPaymentMode();
    getInsurers();

    getBroker();
  }

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

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

  void reset1() {
    print('RESET');
    _formKey.currentState?.reset();
    // Clear all TextEditingControllers
    for (var controller in controllers.values) {
      controller.clear();
    }
    dropDownKey.currentState?.changeSelectedItem(null);
    dropDownKeyInsurer.currentState?.changeSelectedItem(null);

    // Reset dropdowns / selections
    selectedInsurer = null;
    selectedInsPlanType = null;
    selectedEndorsement = null;

    // Reset file selection
    selectedFileNames = null;
    docUploadedFile = null;
    docUploadedFileUrlFromApi = null;

    // Reset selected ID
    selectedId = null;

    // Trigger UI update
    setState(() {});
  }

  void reset() {
    print('RESET');

    _isResetting = true;
    print('_isResetting : $_isResetting');

    controllers['regNo']!.clear();
    _formKey.currentState?.reset();

    fieldErrors.clear();

    // Clear all TextEditingControllers
    for (var controller in controllers.values) {
      controller.clear();
    }
    dropDownKey.currentState?.changeSelectedItem(null);
    dropDownKeyInsurer.currentState?.changeSelectedItem(null);
    dropDownKeyAgent.currentState?.changeSelectedItem(null);
    dropDownKeyInsurerEnqAsgn.currentState?.changeSelectedItem(null);
    dropDownKeyBroker.currentState?.changeSelectedItem(null);

    // Reset dropdowns / selections
    selectedInsurer = null;
    selectedInsPlanType = null;
    selectedEndorsement = null;
    selectedAgent = null;
    selectedBroker = null;
    quotationList.clear();

    // Reset file selection
    selectedFileNames = null;
    docUploadedFile = null;
    docUploadedFileUrlFromApi = null;

    // Reset selected ID
    selectedId = null;

    // Trigger UI update
    setState(() {});
    Future.delayed(Duration(milliseconds: 100), () {
      _isResetting = false; // ✅ safe to enable again
    });
  }

  Future<void> getQuickQuotationList(int managerId) async {
    print('getClaimList called');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.fetchQuickQuotationList(managerId);

      if (response['status'] == 'success') {
        print('getAgentListData - ${response['data']}');
        setState(() {
          getCreatedProposalData = List<Map<String, dynamic>>.from(
            response['data'],
          );
          // print('API Data - $getClaimPolicies');
          //
          originalData = getCreatedProposalData;
          filteredCreatedProposalData = List.from(originalData);
          print('filteredCreatedProposalData - $filteredCreatedProposalData');
        });
      } else {
        // getClaimPolicies = [];
        // originalData = getClaimPolicies;
        // filteredData = List.from(originalData);
        // print('originalData - $getClaimPolicies');
        // print('Request failed: ${response['code']}');
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

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

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

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

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

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

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

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

  void refresh() {}

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

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

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

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

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

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

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

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

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

    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;
      });
    }
  }

  void addQuotationRow() {
    String amountText = controllers["premium_Amount"]?.text ?? "";
    double? amount = double.tryParse(amountText);
    if (selectedInsurer != null &&
        selectedInsPlanType != null &&
        amount != null && amount > 0) {
      setState(() {
        quotationList.add({
          "insurer_id": selectedInsurer,
          "premium_amount": controllers["premium_Amount"]?.text,
          "insurance_plan_type_id": selectedInsPlanType,
          "insurer_name": getInsurerName(selectedInsurer),
          "plan_type_name": getPlanTypeName(selectedInsPlanType),
        });

        // Clear fields after adding
        selectedInsurer = null;
        selectedInsPlanType = null;
        controllers["premium_Amount"]?.clear();
        dropDownKeyInsurerEnqAsgn.currentState?.changeSelectedItem(null);
        dropDownKey.currentState?.changeSelectedItem(null);
      });

      if (isSingleSave) {
        handleDone();
      }
    } else {
      print('Please enter a valid Premium Amount greater than 0');
      ToastHelper.showErrorToast(context, 'Please enter a valid Premium Amount');
      return; // ❌ stop execution
    }
  }

  void removeQuotationRow(int index) {
    setState(() {
      quotationList.removeAt(index);
    });
  }

  String getInsurerName(String? id) {
    if (id == null) return '';
    final insurer = filteredInsurersData.firstWhere(
      (item) => item['id'].toString() == id,
      orElse: () => {},
    );
    return insurer['short_name']?.toString() ?? '';
  }

  String getPlanTypeName(String? id) {
    if (id == null) return '';
    final plan = filteredInsuranceData.firstWhere(
      (item) => item['id'].toString() == id,
      orElse: () => {},
    );
    return plan['insurance_plan_type']?.toString() ?? '';
  }

  void handleDone() {
    if (!_formKey.currentState!.validate()) return;

    // setState(() {
    //   _autoValidate = true; // enable autovalidation after first save attempt
    // });
    setState(() {
      if (_formKey.currentState!.validate()) {
        dataDetails();
        final dataSet = dataDetails();
        print("dataSetAgent - $dataSet");

        if (quotationList.isEmpty) {
          print("Please add at least one quotation before saving.");
          // You can also show a snackbar or dialog
          ToastHelper.showErrorToast(context, 'Add atleast one proposal');
          return; // ❌ stop execution
        }

        // print("managerId - $managerId  ,userId - $userId ");
        createUserData(dataSet);
      } else {
        // isDi sable = false;
      }
    });
  }

  Future<void> createUserData(Map<String, dynamic> userData) async {
    // final bool isUpdating = widget.selectedQuotationFrmListId != null;
    // final id = widget.selectedQuotationFrmListId!;

    print("userDatauserData1 - $userData");
    // final bool isUpdating = widget.selectedQuotationFrmListId != null;
    // final id = widget.selectedQuotationFrmListId; // keep nullable

    // print('id - $id');
    final uri = Uri.parse(
      // isUpdating
      //     ? '${Env.apiUrl}quotation/updateQuotation'
      //     : '${Env.apiUrl}quotation/createQuotation',
      '${Env.apiUrl}enquiry/createEnquiry',
    );
    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 - $userData");

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

    userData.forEach((key, value) {
      if (value is List || value is Map) {
        // List, Map → convert to JSON
        request.fields[key] = jsonEncode(value);
      } else {
        // normal value
        request.fields[key] = value?.toString() ?? "";
      }

      print("➡ $key: ${request.fields[key]}");
    });

    if (docUploadedFile != null) {
      try {
        if (docUploadedFile!.bytes != null) {
          final multipartFile = http.MultipartFile.fromBytes(
            'policy_pdf_file_name',
            docUploadedFile!.bytes!,
            filename: docUploadedFile!.name,
          );
          request.files.add(multipartFile);
        } else if (docUploadedFile!.path != null) {
          final multipartFile = await http.MultipartFile.fromPath(
            'policy_pdf_file_name',
            docUploadedFile!.path!,
            filename: docUploadedFile!.name,
          );
          request.files.add(multipartFile);
        }
        print("📎 File attached: ${docUploadedFile!.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) {
        // dispose();
        print("✅ Agent submitted successfully!");

        print("Response: ${response.body}");
        // ToastHelper.showErrorToast(context, 'Proposal Created');
        reset();

        getQuickQuotationList(managerId);

        // Navigator.of(context).pop();
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        final responseBody = jsonDecode(response.body);
        dynamic msg = responseBody['data'];
        print("❌ Submission failed. Status: ${response.statusCode}");
        print("Body: ${response.body}");

        ToastHelper.showErrorToast(context, 'Proposal Creation Failed');
      }
    } catch (e) {
      print("🔥 Error submitting user: $e");
    }
  }

  Future<void> handleProceed(val, id) async {
    print('handleProceed -1 ');
    final String apiUrldata;
    apiUrldata = '${Env.apiUrl}quotation/acceptOrRejectQuotation';


    // final token = await getToken(); // Fetch token
    print('handleProceed -2 ');
    if (_token == null) {
      throw Exception('Token not found. Please log in.');
    }

    final Map<String, dynamic> data = {
      "id": id,
      // "status": 'Accepted',
      "status": val,
      "action_by": userId,
      // "action_user": (role == 'agent') ? 'agent' : 'handler',
      "action_user": roleId,
    };
    print('handleProceed -3 ');
    // data['id'] = selectedId; // Add plan_id for update
    // data['status'] = val;

    print("data-------  $data");

    try {
      final response = await http.post(
        Uri.parse(apiUrldata),
        headers: {
          'Authorization': 'Bearer $_token',
          'Content-Type': 'application/json',
          'app-signature': Env.App_Signature,
        },
        body: jsonEncode(data), // Convert map to JSON
      );

      if (response.statusCode == 200) {
        print("Response: ${response.body}");

        ToastHelper.showSuccessToast(context, 'Status Updated');
        print("tre1");
        selectedId = null; // just update field
        Navigator.of(context).pop();
        // final prefs = await SharedPreferences.getInstance();
        // await prefs.setString('QuoteKeyProvider', 'fromQuickQuote');

        WidgetsBinding.instance.addPostFrameCallback((_) {
          // Now safe to do navigation + provider updates
          final container = ProviderScope.containerOf(context);
          container.read(enquiryRefreshProvider.notifier).state = true;

          context.go('/enquiryForStaff');
        });

        print("tre11");
        getQuickQuotationList(managerId);
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        final responseBody = jsonDecode(response.body);
        dynamic msg = responseBody['data'];
        ToastHelper.showErrorToast(context, 'Status Updation Failed');
        print("Failed to submit plan. Status: ${response.statusCode}");
        print("Error: ${response.body}");
      }
    } catch (e) {
      print(" Error submitting Staff: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return SelectionArea(
      child: FocusTraversalGroup(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.all(8.0),

            decoration: BoxDecoration(
              // color: Colors.amber,
              gradient: const LinearGradient(
                colors: [
                  Color(0xFFE4F5F1), // very light teal
                  // Color(0xFF8CCABE), // very light teal
                  // Color(0xFFC4E7DA), // very light teal
                  Color(0xFFE8F7F4),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(8.0),
            ),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      buildAgentName(context),
                      const SizedBox(width: 20),
                      buildVehicleNumber(context),
                    ],
                  ),

                  Divider(thickness: 0.3, color: Colors.blueGrey.shade100),
                  SizedBox(height: 2),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      buildInsurer(context),
                      const SizedBox(width: 20),
                      buildInsurancePlanType(context),
                      const SizedBox(width: 20),
                      buildPremiumAmnt(context),
                      const SizedBox(width: 10),
                      Row(
                        children: [
                          // SizedBox(width: 10),
                          // GestureDetector(
                          //   onTap: () {
                          //     setState(() {
                          //       isSingleSave = true;
                          //     });
                          //     addQuotationRow();
                          //   },
                          //   child: Container(
                          //     padding: const EdgeInsets.symmetric(
                          //       horizontal: 5,
                          //       vertical: 5,
                          //     ),
                          //     decoration: BoxDecoration(
                          //       borderRadius: BorderRadius.circular(5.0),
                          //       color: Colors.blue,
                          //     ),
                          //     child: Text(
                          //       'Save',
                          //       style: GoogleFonts.poppins(
                          //         color: Colors.white,
                          //         fontSize: 10,
                          //       ),
                          //     ),
                          //   ),
                          // ),
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue,
                              padding: const EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 4,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5),
                              ),
                            ),
                            onPressed: () {
                              setState(() {
                                isSingleSave = true;
                              });
                              addQuotationRow();
                            },
                            child: Text(
                              'Save',
                              style: GoogleFonts.poppins(
                                color: Colors.white,
                                fontSize: 10,
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          GestureDetector(
                            onTap: () {
                              addQuotationRow();
                            },
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 5,
                                vertical: 5,
                              ),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(20.0),
                                color: Colors.blue,
                              ),
                              child: Icon(
                                Icons.add,
                                color: Colors.white,
                                size: 14,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),

                  if (quotationList.isNotEmpty) ...[
                    const SizedBox(height: 10),

                    Text(
                      'Added Quote(${quotationList.length})',
                      style: GoogleFonts.poppins(
                        fontSize: 12,
                        color: Color(0xFF334155),
                      ),
                    ),
                    const SizedBox(height: 10),
                    GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: quotationList.length,
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3, // 👈 3 cards per row
                            mainAxisSpacing: 16,
                            crossAxisSpacing: 16,
                            childAspectRatio:
                                3, // 👈 controls card shape (adjust if needed)
                          ),
                      itemBuilder: (context, index) {
                        final item = quotationList[index];

                        return Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: const Color(0xFFE2E8F0)),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.05),
                                blurRadius: 1,
                                offset: const Offset(0, 1),
                              ),
                            ],
                          ),
                          child: Stack(
                            children: [
                              /// 🟦 Card Content
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    item["insurer_name"],
                                    style: GoogleFonts.poppins(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xFF334155),
                                    ),
                                  ),
                                  const SizedBox(height: 6),

                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        item["plan_type_name"],
                                        style: GoogleFonts.poppins(
                                          fontSize: 11,
                                          fontWeight: FontWeight.w400,
                                          color: Colors.black,
                                        ),
                                      ),
                                      Text(
                                        "₹${item["premium_amount"].toString().replaceAll("\$", "")}",
                                        style: GoogleFonts.poppins(
                                          fontSize: 11,
                                          fontWeight: FontWeight.w400,
                                          color: Colors.blueGrey,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),

                              /// ❌ Delete Icon
                              Positioned(
                                top: 0,
                                right: 0,
                                child: GestureDetector(
                                  onTap: () => removeQuotationRow(index),
                                  child: Container(
                                    padding: const EdgeInsets.all(2),
                                    // decoration: BoxDecoration(
                                    //   color: Colors.red.shade50,
                                    //   borderRadius: BorderRadius.circular(4),
                                    // ),
                                    child: Icon(
                                      Icons.close,
                                      size: 16,
                                      color: Colors.red.shade700,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ],

                  // ✅ END OF TABLE CODE
                  SizedBox(height: 20),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF2E7D6E),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 18,
                            vertical: 12,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6),
                          ),
                        ),
                        onPressed: handleDone,
                        child: Text(
                          'Save All Quotes',
                          style: GoogleFonts.poppins(
                            color: Colors.white,
                            fontSize: 13,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: 10),
          Container(
            padding: EdgeInsets.all(8.0),
            width: double.infinity,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8.0),
              boxShadow: [
                BoxShadow(
                  color: Colors.blueGrey.shade100,
                  spreadRadius: 0.2,
                  blurRadius: 1,
                  offset: const Offset(0, 1), // Horizontal, Vertical
                ),
              ],
            ),
            child: DataTable(
              headingRowColor: WidgetStatePropertyAll(Color(0xFFEFF6FF)),
              headingRowHeight: 30,
              dividerThickness: 0.3,
              columnSpacing: 10,
              columns: [
                DataColumn(label: Text("Partner", style: _tableHeaderStyle)),
                DataColumn(label: Text("Vehicle Number", style: _tableHeaderStyle)),
                DataColumn(label: Text("Insurer", style: _tableHeaderStyle)),
                DataColumn(label: Text("Plan Type", style: _tableHeaderStyle)),
                DataColumn(label: Text("Premium", style: _tableHeaderStyle)),
                DataColumn(label: Text("Action", style: _tableHeaderStyle)),
              ],
              rows: filteredCreatedProposalData.expand((item) {
                List quotationList = item["quotation_data"] ?? [];

                if (quotationList.isEmpty) {
                  // If no quotation, show single empty row
                  return [
                    DataRow(
                      cells: [
                        // DataCell(
                        //   Text(
                        //     item["agent_name"] ?? "-",
                        //     style: _tableDataStyle,
                        //   ),
                        // ),
                        DataCell(
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Top: Agent Name
                              Text(
                                item['agent_name'] ?? '-',
                                style: _tableDataStyle,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),

                              // Bottom: Agent Code (light weight)
                              if (item['agent_code'] != null)
                                Text(
                                  item['agent_code'],
                                  style: _tableDataStyle.copyWith(
                                    fontSize: 11,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                            ],
                          ),
                        ),
                        DataCell(
                          Text(item["reg_no"] ?? "-", style: _tableDataStyle),
                        ),
                        DataCell(Text("-", style: _tableDataStyle)),
                        DataCell(Text("-", style: _tableDataStyle)),
                        DataCell(Text("-", style: _tableDataStyle)),
                        DataCell(
                          ElevatedButton(
                            onPressed: () {
                              print('handleProceed - Accepted');
                              // Navigator.pop(context);
                              Navigator.of(context).pop();

                              context.go('/enquiryForStaff');
                              // handleProceed('Accepted');
                            },
                            child: Text(
                              'PROCEED',
                              style: GoogleFonts.poppins(
                                fontSize: 10,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ];
                }

                // Multiple quotations — return multiple DataRow
                return quotationList.map<DataRow>((quote) {
                  return DataRow(
                    cells: [
                      DataCell(
                        // Text(item["agent_name"] ?? "-", style: _tableDataStyle),
                          Text(
                          (item['agent_code'] != null && item['agent_name'] != null)
                              ? '${item['agent_code']} - ${item['agent_name']}'
                              : (item['agent_name'] ?? '-'),
                          style: _tableDataStyle,
                          ),
                      ),
                      DataCell(
                        Text(item["reg_no"] ?? "-", style: _tableDataStyle),
                      ),
                      DataCell(
                        Text(
                          quote["insurer_short_name"] ?? "-",
                          style: _tableDataStyle,
                        ),
                      ),
                      DataCell(
                        Text(
                          quote["insurance_plan_type"] ?? "-",
                          style: _tableDataStyle,
                        ),
                      ),
                      DataCell(
                        Text(
                          "${quote["premium_amount"]}",
                          style: _tableDataStyle,
                        ),
                      ),
                      DataCell(
                        ElevatedButton(
                          onPressed: () {
                            print('handleProceed - Accepted');
                            handleProceed('Accepted', quote['id']);
                          },
                          child: Text(
                            'PROCEED',
                            style: GoogleFonts.poppins(
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                }).toList();
              }).toList(),
            ),
          ),
        ],
      ),
    ),);
  }

  Widget buildIdv(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('IDV *', style: _textStyle),
        SizedBox(height: 10),
        ThemedFormField(
          controller: controllers['idv']!,

          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
          ],
          validator: (value) => Validators.doubleNumber(value, "IDV"),
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          // validator: (value) => Validators.number(value, "IDV"),
          // backgroundColor: Color(0xFFEDF6F5),
          // readOnly: true,
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.08,
          // txtheight: 35,
        ),
      ],
    );
  }

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

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

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

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

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

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

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

  Widget buildVehicleNumber(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Vehicle Number *', style: _textStyle),

        SizedBox(height: 5),
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.2,
          height: 30,
          child: ThemedFormInlineField(
            controller: controllers['regNo']!,
            hintText: 'Vehicle Number',
            borderColor: Color(0xFFE2E8F0),
            highlightColor: Color(0xFF50A398),
            padVertical: 10,
            isdense: true,
            errFieldHgt: 0.0,
            errFieldFont: 0.0,
            inputFormatters: [
              UpperCaseTextFormatter(), // 👈 custom formatter for uppercase
              FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9- ]')),
            ],
            onChanged: (val) async {
              if (_isResetting) {
                print("Skipping API because _isResetting = true");
                return;
              }
              print('Vehicle - $val');

              if (val != null) {
                final res = await apiService.CheckDuplicate(context, val);
                print('Vehicle res- $res');

                if (res["message"] != null && res["message"] != "") {
                  ToastHelper.showErrorToast(context, res['message']);
                  setState(() {
                    fieldErrors['regNo'] = res['message']; // store API message
                  }); // 🔥 store backend message
                } else {
                  setState(() {
                    fieldErrors['regNo'] = res['message']; // store API message
                  });
                }
              }
            },
            validator: (value) {
              // Show backend validation message
              if (fieldErrors['regNo'] != null &&
                  fieldErrors['regNo']!.isNotEmpty) {
                return fieldErrors['regNo']; // show API message
              }

              return Validators.requiredField(value, "regNo");
            },
            // validator: (value) => Validators.requiredVechileNum(value, "regNo"),
            widthNone: true,
          ),
        ),
      ],
    );
  }

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

        SizedBox(height: 5),
        Container(
          height: 30,
          width: MediaQuery.of(context).size.width * 0.12,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyInsurerEnqAsgn,
            selectedItem: selectedInsurerd.isNotEmpty ? selectedInsurerd : null,
            items: (filter, infiniteScrollProps) async {
              if (filter.isEmpty) {
                return filteredInsurersData;
              }
              return filteredInsurersData.where((item) {
                return item['short_name'].toString().toLowerCase().contains(
                  filter.toLowerCase(),
                );
              }).toList();
            },
            itemAsString: (val) => val['short_name'].toString(), // what to show
            compareFn: (item, selectedItem) =>
                item['id'] == selectedItem['id'], // ✅ compare by id
            // validator: (val) {
            //   if (val == null) {
            //     return "Required"; // ✅ error message
            //   }
            //   return null;
            // },
            suffixProps: DropdownSuffixProps(
              // make sure the dropdown button is visible
              dropdownButtonProps: DropdownButtonProps(
                isVisible: true,
                padding: EdgeInsets.zero, // remove default padding
                constraints: const BoxConstraints(
                  // shrink icon tap area
                  minWidth: 12,
                  minHeight: 12,
                ),
                iconSize: 15, // smaller icon
                // icon: const Icon(Icons.arrow_drop_down),
              ),
            ),

            dropdownBuilder: (context, selectedItem) {
              return Container(
                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
                alignment: Alignment.centerLeft,
                height: 22, // 👈 FORCE HEIGHT
                child: Text(
                  selectedItem?['short_name'] ?? '',
                  style: GoogleFonts.poppins(fontSize: 11),
                  overflow: TextOverflow.ellipsis,
                ),
              );
            },

            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Insurer",
                  ).copyWith(
                    errorStyle: GoogleFonts.poppins(fontSize: 0, height: 0.0),
                    filled: true,
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    // contentPadding: EdgeInsets.zero,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 4,
                      vertical: 1,
                    ),
                  ),
            ),
            popupProps: PopupProps.menu(
              fit: FlexFit.loose,
              searchDelay: Duration(milliseconds: 200),
              constraints: BoxConstraints(maxHeight: 250),
              menuProps: MenuProps(
                backgroundColor:
                    Colors.white, // 👈 sets dropdown background to white
              ),
              showSearchBox: true,
              searchFieldProps: TextFieldProps(
                autofocus: true,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(1),
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Search Insurer...",
                  hintStyle: GoogleFonts.inter(
                    fontSize: 11,
                    color: Colors.black,
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                    ), // 👈 Normal border
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1.5,
                    ), // 👈 Focused border
                  ),
                ),
              ),

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

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

  Widget buildPremiumAmnt(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Premium Amount *', style: _textStyle),
        SizedBox(height: 5),
        SizedBox(
          height: 30,
          child: ThemedFormField(
            controller: controllers['premium_Amount']!,
            borderColor: Color(0xFFE2E8F0),
            highlightColor: Color(0xFF50A398),
            bordedRad: 5,
            // backgroundColor: Color(0xFFEDF6F5),
            inputFormatters: [
              // FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
              FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}$')),
            ],
            // validator: (value) =>
            //     Validators.doubleNumber(value, "PremiumAmount"),
            // validator: (value) => Validators.number(value, "PremiumAmount "),
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.12,
            // txtheight: 35,
          ),
        ),
      ],
    );
  }

  Widget buildInsurancePlanType(context) {
    Map<String, dynamic>? selectedVehicle = filteredInsuranceData.firstWhere(
      (item) => item['id'].toString() == selectedInsPlanType,
      orElse: () => {},
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("Plan Type *", style: _textStyle),
        SizedBox(height: 5),
        SizedBox(
          // color: Colors.white,
          width: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.12,
          height: 30,
          child: FocusableActionDetector(
            focusNode: partnerFocusNode,
            autofocus: false,
            onShowFocusHighlight: (hasFocus) {
              setState(() {
                focusedBorder:
                OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: const BorderSide(
                    color: Color(0xFF50A398),
                    width: 2,
                  ),
                );
              }); // redraw to show highlight border
            },
            child: DropdownSearch<Map<String, dynamic>>(
              key: dropDownKey,
              // focusNode: partnerFocusNode,
              selectedItem: selectedVehicle.isNotEmpty ? selectedVehicle : null,
              // items: (filter, infiniteScrollProps) {
              //   return filteredInsuranceData;
              // },
              items: (filter, infiniteScrollProps) async {
                if (filter.isEmpty) {
                  return filteredInsuranceData;
                }
                return filteredInsuranceData.where((item) {
                  return item['name'].toString().toLowerCase().contains(
                    filter.toLowerCase(),
                  );
                }).toList();
              },

              suffixProps: DropdownSuffixProps(
                // make sure the dropdown button is visible
                dropdownButtonProps: DropdownButtonProps(
                  isVisible: true,
                  padding: EdgeInsets.zero, // remove default padding
                  constraints: const BoxConstraints(
                    // shrink icon tap area
                    minWidth: 12,
                    minHeight: 12,
                  ),
                  iconSize: 15, // smaller icon
                  // icon: const Icon(Icons.arrow_drop_down),
                ),
              ),
              itemAsString: (val) => val['insurance_plan_type'].toString(),
              compareFn: (item, selectedItem) =>
                  item['id'] == selectedItem['id'], // ✅ compare by id
              // validator: (val) {
              //   if (val == null) {
              //     return "Required"; // ✅ error message
              //   }
              //   return null;
              // },
              decoratorProps: DropDownDecoratorProps(
                decoration:
                    AppInputDecorations.dropdownDecoration(
                      label: "Select Plan Type",
                    ).copyWith(
                      errorStyle: GoogleFonts.poppins(fontSize: 0, height: 0.0),
                      filled: true,
                      fillColor:
                          Colors.white, // 👈 makes the dropdown input white
                      isDense: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Color(0xFFE2E8F0),
                          width: 0.5,
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Color(0xFFE2E8F0),
                          width: 0.5,
                        ),
                      ),
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 6,
                      ),
                    ),
              ),
              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: BoxConstraints(maxHeight: 250),
                menuProps: MenuProps(
                  backgroundColor:
                      Colors.white, // 👈 sets dropdown background to white
                ),
                showSearchBox: true,
                searchFieldProps: TextFieldProps(
                  autofocus: true,
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(1),
                    filled: true,
                    fillColor: Colors.white,
                    hintText: "Search Plan Type ...",
                    hintStyle: GoogleFonts.inter(
                      fontSize: 12,
                      color: Colors.black,
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.white,
                      ), // 👈 Normal border
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.white,
                        width: 1.5,
                      ), // 👈 Focused border
                    ),
                  ),
                ),

                itemBuilder: (context, item, isDisabled, isSelected) {
                  return Container(
                    // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 3,
                    ),
                    child: Text(
                      item['insurance_plan_type'].toString(),
                      style: GoogleFonts.inter(
                        fontSize: 12,
                        color: Colors.black,
                      ),
                    ),
                  );
                },
                // searchFieldProps: TextFieldProps(
                //   decoration: InputDecoration(
                //     filled: true,
                //     fillColor: Colors.white,
                //     hintText: "Search Plan Type...",
                //     enabledBorder: OutlineInputBorder(
                //       borderSide: BorderSide(
                //         color: Colors.white,
                //       ), // 👈 Normal border
                //     ),
                //     focusedBorder: OutlineInputBorder(
                //       borderSide: BorderSide(
                //         color: Colors.white,
                //         width: 1.5,
                //       ), // 👈 Focused border
                //     ),
                //   ),
                // ),
                // constraints: BoxConstraints(),
              ),

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

  Widget _rowLabelValue(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          value,
          style: GoogleFonts.poppins(
            fontSize: 13,
            fontWeight: FontWeight.w600,
            color: Colors.black,
          ),
        ),
      ],
    );
  }

  // ------------------- STyle ---------------------------------

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

  static final TextStyle _tableHeaderStyle = GoogleFonts.poppins(
    fontSize: 11.5,
    color: Color(0XFF475569),
    fontWeight: FontWeight.w500,
  );

  static final TextStyle _tableDataStyle = GoogleFonts.poppins(
    fontSize: 11.5,
    color: Color(0XFF334155),
    fontWeight: FontWeight.w400,
  );
}

class QuotationRow {
  TextEditingController premiumCtrl = TextEditingController();
  String? insurerId;
  String? planTypeId;
}
