import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:nhance_partner/data/utils/toastNotification.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../core/services/api_service.dart';
import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/validators.dart';
import '../../../providers/manager_provider.dart';
import '../../../providers/userRoleProvider.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 RaiseEnqForm extends ConsumerStatefulWidget {
  final Function(Map<String, dynamic> data) onSubmit;
  const RaiseEnqForm({super.key, required this.onSubmit});
  @override
  ConsumerState<RaiseEnqForm> createState() => RaiseEnqFormState();
}

class RaiseEnqFormState extends ConsumerState<RaiseEnqForm> {
  late ApiService apiService;
  dynamic userId;
  dynamic idPrimary;
  dynamic managerId;
  dynamic dashboardKey;
  dynamic SelectedStatus;
  dynamic SelectedStaffId;
  dynamic handlerId;
  String? _token;
  final _formKey = GlobalKey<FormState>();
  Map<String, String?> fieldErrors = {};

  bool _isResetting = false;

  Map<String, TextEditingController> controllers = {};
  List<String> tabHeader = [
    'startDate',
    'endDate',
    'name',
    'email',
    'mobile',
    'code',
    'address',
    'regNo',
    'remarks',
  ];

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

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

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

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

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

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

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

  List<Map<String, dynamic>> getStaffDetailsDataEnqAsgn = [];
  List<Map<String, dynamic>> filteredStaffDataEnqAsgn = [];

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

  String? selectedVehicleType;
  String? selectedInsurer;
  String? selectedAgent;
  dynamic roleId;

  bool isLoading = false;

  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_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,
      "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();
    }
    _initializeToken();

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

      final prefs = await SharedPreferences.getInstance();
      dashboardKey = prefs.getString('dashboardKeyProvider');
      final dashboardStatus = prefs.getString('dashboardStatusProvider');
      final dashboardStaffId = prefs.getString('dashboardStaffIdProvider');

      print('handlerIdENQ - $handlerId');
      print("C72 => r : $roleId | uId: $userId !mID : $managerId ");

      print('dashboardKey - $dashboardKey');
      print('dashboardStatus - $dashboardStatus');
      print('dashboardStaffId - $dashboardStaffId');

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

      final userID = ref.watch(userIdProvider);

      print("managerId - $managerId");
      if (userID != null) {
        print('hansles');
        getStaffDetailsForEnquiryAssignment(userID);
      }
      getBroker();
    });

    getVehicleType();
    getInsurers();
  }

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

  void resetFormFields() {
    _isResetting = true;
    print('_isResetting : $_isResetting');
    ;

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

    fieldErrors.clear();

    // 1. Reset all text controllers
    controllers.forEach((key, controller) {
      controller.clear();
    });

    // 2. Reset dropdown selections
    setState(() {
      selectedAgent = null;
      selectedInsurer = null;
      // Add any other dropdowns
    });

    // 3. Reset form validation
    _formKey.currentState?.reset();

    setState(() {});

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

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

    try {
      final response = await apiService.fetchMasterDropDown('vehicleType','dropdown');

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

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

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

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

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

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

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

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

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

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


  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> getStaffDetailsForEnquiryAssignment(int id) async {
    print('getStaffDetailsForEnquiryAssignment called By handler');
    setState(() {
      isLoading = true;
    });

    try {
      // final response = await apiService.fetchStaffUserList(id, role);
      final response = await apiService.fetchStaffListForEnquiryAssignDropDown(
        managerId,
        id,
        roleId,
      );

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

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

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SelectionArea(
      child:Container(
      // color: Color(0xFFFCFCFC),
      // margin: const EdgeInsets.symmetric(vertical: 8),
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 25),
      // height: MediaQuery.of(context).size.height * 0.16,
      decoration: BoxDecoration(
        color: Colors.white,
        // color: Colors.amber,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            // color: Colors.black.withOpacity(0.08),
            color: Color(0xFF2E7D6E),
            // color: Color(0xFFDCFCE7),
            blurRadius: 0,
            spreadRadius: 0.1,
            // blurRadius: 0.1,
            // spreadRadius: 1,
            offset: const Offset(0, 0.5), // soft drop shadow
          ),
        ],
      ),
      child: FocusTraversalGroup(
        child: Form(
          key: _formKey,
          child: Container(
            // color: Colors.amber.shade100,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if (roleId != 'staff') ...[buildSelectStaffMem(context)],
                buildAgentName(context, fromHeader: true),
                buildBroker(context),
                buildInsurer(context, fromHeader: true),
                buildVehicleType(context),
                // buildInsuredName(context, fromHeader: true),
                buildVehicleNumber(context),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    buildRefresh(context),
                    SizedBox(width: 5),
                    buildSave(context),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    ),);
  }

  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: _subLabelTimeStyle),

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

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

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

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

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

  Widget buildInsuredName(BuildContext context, {fromHeader = true}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Insured', style: _subLabelTimeStyle),

        SizedBox(height: 5),
        SizedBox(
          width: MediaQuery.of(context).size.width * 0.15,

          child: ThemedFormInlineField(
            controller: controllers['name']!,
            hintText: 'Insured Name',
            // errorText: fieldErrors['name'],
            borderColor: Color(0xFFE2E8F0),
            highlightColor: Color(0xFF50A398),
            padVertical: 13,
            isdense: true,
            validator: (value) => Validators.requiredField(value, "name"),
            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: _subLabelTimeStyle),

        SizedBox(height: 5),
        Container(
          // height: 30,
          width: MediaQuery.of(context).size.width * 0.12,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyInsurerEnqAsgn,
            selectedItem: selectedInsurerd.isNotEmpty ? selectedInsurerd : null,
            // items: (filter, infiniteScrollProps) {
            //   return filteredInsurersData;
            // },
            // 👇 Enable async filtering based on user input
            items: (filter, infiniteScrollProps) async {
              if (filter.isEmpty) {
                return filteredInsurersData;
              }
              return filteredInsurersData.where((item) {
                return item['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) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null
                    ? selectedItem['short_name'].toString()
                    : "",
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Insurer",
                  ).copyWith(
                    filled: true,
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                  ),
            ),

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

              itemBuilder: (context, item, isDisabled, isSelected) {
                return Container(
                  // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 3,
                  ),
                  child: Text(
                    item['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 buildVehicleNumber(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width * 0.15,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Vehicle Number *', style: _subLabelTimeStyle),

          SizedBox(height: 5),
          ThemedFormField(
            controller: controllers['regNo']!,
            borderColor: Color(0xFFE2E8F0),
            highlightColor: Color(0xFF50A398),
            hintText: 'Vehicle Number',
            txtwidth: MediaQuery.of(context).size.width * 0.26,
            verticalPad: 15,
            isdense: true,
            validator: (value) {
              // Show backend validation message
              if (fieldErrors['regNo'] != null &&
                  fieldErrors['regNo']!.isNotEmpty) {
                return fieldErrors['regNo']; // show API message
              }

              return Validators.requiredField(value, "regNo");
            },
            inputFormatters: [
              UpperCaseTextFormatter(), // 👈 custom formatter for uppercase
              FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9- ]')),
            ],
            // validator: (value) => Validators.requiredField(value, "regNo"),
            onChanged: (val) async {
              if (_isResetting) {
                print("Skipping API because _isResetting = true");
                return;
              }
              print('Vehicle - $val');
              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
                });
              }
            },
          ),
          // ThemedFormInlineField(
          //   controller: controllers['regNo']!,
          //
          //   hintText: 'Vehicle Number',
          //   borderColor: Color(0xFFE2E8F0),
          //   highlightColor: Color(0xFF50A398),
          //   padVertical: 13,
          //   isdense: true,
          //   inputFormatters: [
          //     UpperCaseTextFormatter(), // 👈 custom formatter for uppercase
          //     FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9- ]')),
          //   ],
          //   // validator: (value) => Validators.requiredField(value, "regNo"),
          //   onChanged: (val) async {
          //     if (_isResetting) {
          //       print("Skipping API because _isResetting = true");
          //       return;
          //     }
          //     print('Vehicle - $val');
          //     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");
          //   },
          //   // txtheight: 30,
          //   // txtwidth: MediaQuery.of(context).size.width * 0.01,
          // ),
        ],
      ),
    );
  }

  Widget buildSelectStaffMem(ctx) {
    Map<String, dynamic>? selectedVehicle;
    try {
      selectedVehicle = filteredStaffDataEnqAsgn.firstWhere(
        (item) => item['id'].toString() == selectedStaff,
      );
    } catch (e) {
      selectedVehicle = null; // ✅ fallback
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Assigned To *', style: _subLabelTimeStyle),

        SizedBox(height: 5),
        SizedBox(
          // height: 30,
          width: MediaQuery.of(context).size.width * 0.15,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownSelectStaffKey,

            // selectedItem: selectedVehicle.isNotEmpty ? selectedVehicle : null,
            selectedItem: selectedVehicle,
            // items: (filter, infiniteScrollProps) {
            //   return filteredStaffDataEnqAsgn;
            // },
            items: (filter, infiniteScrollProps) async {
              if (filter.isEmpty) {
                return filteredStaffDataEnqAsgn;
              }
              return filteredStaffDataEnqAsgn.where((item) {
                return item['name'].toString().toLowerCase().contains(
                  filter.toLowerCase(),
                );
              }).toList();
            },

            itemAsString: (val) => val['name'].toString(),
            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),
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Select Staff Member",
                  ).copyWith(
                    filled: true,
                    fillColor:
                        Colors.white, // 👈 makes the dropdown input white
                    isDense: true,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Color(0xFFE2E8F0),
                        width: 0.5,
                      ),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 6,
                    ),
                  ),
            ),
            dropdownBuilder: (context, selectedItem) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null ? selectedItem['name'].toString() : "",
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            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 Staff ...",
                  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
                  ),
                ),
              ),
              // 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: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        item['name'].toString(),
                        style: GoogleFonts.inter(
                          fontSize: 12,
                          color: Colors.black,
                        ),
                      ),

                      Text(
                        "(${item['today_assigned']} / ${item['total_pending']})",
                        style: GoogleFonts.poppins(
                          fontSize: 10,
                          color: Colors.blueGrey.shade200,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),

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

  Widget buildBroker(BuildContext context) {
    Map<String, dynamic>? selectedBrokers = filteredBrokerData.firstWhere(
      (item) => item['id'].toString() == selectedBroker,
      orElse: () => {},
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Broker *', style: _subLabelTimeStyle),

        SizedBox(height: 5),
        SizedBox(
          // height: 30,
          width: MediaQuery.of(context).size.width * 0.12,
          child: DropdownSearch<Map<String, dynamic>>(
            key: dropDownKeyBroker,
            selectedItem: selectedBrokers.isNotEmpty ? selectedBrokers : null,
            items: (filter, infiniteScrollProps) {
              return filteredBrokerData;
            },

            itemAsString: (val) => val['name'].toString(), // what to show
            compareFn: (item, selectedItem) =>
                item['id'] == selectedItem['id'], // ✅ compare by id
            validator: (val) {
              if (val == null) {
                return "Required"; // ✅ error message
              }
              return null;
            },
            suffixProps: DropdownSuffixProps(
              // make sure the dropdown button is visible
              dropdownButtonProps: DropdownButtonProps(
                isVisible: true,
                padding: EdgeInsets.zero, // remove default padding
                constraints: const BoxConstraints(
                  // shrink icon tap area
                  minWidth: 12,
                  minHeight: 12,
                ),
                iconSize: 15, // smaller icon
                // icon: const Icon(Icons.arrow_drop_down),
              ),
            ),
            dropdownBuilder: (context, selectedItem) => Align(
              alignment: Alignment.centerLeft,
              child: Text(
                selectedItem != null ? selectedItem['name'].toString() : "",
                style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                softWrap: false,
              ),
            ),
            decoratorProps: DropDownDecoratorProps(
              decoration:
                  AppInputDecorations.dropdownDecoration(
                    label: "Select Broker",
                  ).copyWith(
                    filled: true,
                    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,
                style: GoogleFonts.inter(fontSize: 11, color: Colors.black),
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(1),
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Search Broker...",
                  hintStyle: GoogleFonts.inter(
                    fontSize: 12,
                    color: Colors.black,
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                    ), // 👈 Normal border
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1.5,
                    ), // 👈 Focused border
                  ),
                ),
              ),

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

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

  Widget buildVehicleType(BuildContext context) {
      Map<String, dynamic>? selectedVehicleTypes = filteredVehicleData.firstWhere(
            (item) => item['id'].toString() == selectedVehicleType,
        orElse: () => {},
      );
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Vehicle Type *', style: _subLabelTimeStyle),
          SizedBox(height: 5),
          SizedBox(
            // height: 30,
            width: MediaQuery.of(context).size.width * 0.12,
            child: DropdownSearch<Map<String, dynamic>>(
              key: dropDownSelectVehicleTypeKey,
              selectedItem: selectedVehicleTypes.isNotEmpty ? selectedVehicleTypes : null,
              items: (filter, infiniteScrollProps) {
                return filteredVehicleData;
              },

              itemAsString: (val) => val['vehicle_type'].toString(), // what to show
              compareFn: (item, selectedItem) =>
              item['vehicle_type'].toString() == selectedItem['vehicle_type'].toString(),
              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['vehicle_type'].toString() : "",
                  style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  softWrap: false,
                ),
              ),
              decoratorProps: DropDownDecoratorProps(
                decoration:
                AppInputDecorations.dropdownDecoration(
                  label: "Select Vehicle Type",
                ).copyWith(
                  filled: true,
                  fillColor:
                  Colors.white, // 👈 makes the dropdown input white
                  isDense: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Color(0xFFE2E8F0),
                      width: 0.5,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Color(0xFFE2E8F0),
                      width: 0.5,
                    ),
                  ),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 6,
                  ),
                ),
              ),

              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: BoxConstraints(maxHeight: 250),
                menuProps: MenuProps(
                  backgroundColor:
                  Colors.white, // 👈 sets dropdown background to white
                ),
                showSearchBox: true,
                searchFieldProps: TextFieldProps(
                  autofocus: true,
                  style: GoogleFonts.inter(fontSize: 11, color: Colors.black),
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(1),
                    filled: true,
                    fillColor: Colors.white,
                    hintText: "Search Vehicle 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['vehicle_type'].toString(),
                      style: GoogleFonts.inter(fontSize: 12, color: Colors.black),
                    ),
                  );
                },
                // constraints: BoxConstraints(),
              ),

              onChanged: (val) {
                if (val != null) {
                  // print("Selected vehicletype : ${val['vehicle_type']}");
                  // print("Id: ${val['id']}");
                  // print("Value: ${val}");
                  selectedVehicleType = val['id'];
                }
              },
            ),
          ),
        ],
      );
    }

  Widget buildSave(context) {
    return InkWell(
      onTap: () {
        if (!_formKey.currentState!.validate()) return;

        final dataSet = dataDetails();

        print('checking dataSet $dataSet');

        widget.onSubmit(dataSet);
        resetFields();
      },
      child: Container(
        padding: EdgeInsets.all(5.0),
        decoration: BoxDecoration(
          color: const Color(0xFF2E7D6E),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: Text('Create', style: GoogleFonts.inter(color: Colors.white)),
      ),
    );
  }

  Widget buildRefresh(context) {
    return InkWell(
      onTap: () {
        resetFields();
      },
      child: Container(
        padding: EdgeInsets.all(6.0),
        decoration: BoxDecoration(
          color: const Color(0xFF2E7D6E),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: Icon(Icons.refresh, size: 18, color: Colors.white),
      ),
    );
  }

  void resetFields() {
    print('Field ReSET');
    // 1. Reset all text controllers
    controllers.forEach((key, controller) {
      controller.clear();
    });

    // 2. Reset dropdown selections
    setState(() {
      selectedAgent = null;
      selectedInsurer = null;
      selectedStaff = null;
      selectedStaffName = null;
      selectedVehicleType = null;
      selectedRegNum = null;
      selectedBroker = null;
    });

    // 3. Reset dropdown UI (important for DropdownSearch)
    dropDownKeyAgent.currentState?.clear();
    dropDownKeyInsurerEnqAsgn.currentState?.clear();
    dropDownSelectStaffKey.currentState?.clear();
    dropDownSelectVehicleTypeKey.currentState?.clear();
    dropDownKeyInsurer.currentState?.clear();
    dropDownKey.currentState?.clear();
    dropDownKeyBroker.currentState?.clear();

    // 4. Reset validators
    _formKey.currentState?.reset();
  }

  final _subLabelTimeStyle = GoogleFonts.inter(
    fontSize: 11.5,
    fontWeight: FontWeight.w500,
    color: Color(0xFF2E7D6E),
    // color: Color(0xFF1E293B),
  );
}
