import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import '../../core/services/api_service.dart';
import '../layouts/responsive_layout.dart';
import '../providers/manager_provider.dart';
import '../providers/userRoleProvider.dart';
import '../themes/indicators/date_field_theme.dart';
import '../themes/indicators/input_field_decoration.dart';

// class DateFilterRow extends StatelessWidget {
//   final TextEditingController startController;
//   final String? selectedStatusVal;
//   final TextEditingController endController;
//   final ValueChanged<String?>? onStatusChanged;
//   final String? dataFrom;
//   final VoidCallback onFilter;
//   final VoidCallback onRefresh;
//   final GlobalKey<FormState> formKey;
//   final bool isMobile;
//
//   DateFilterRow({
//     super.key,
//     required this.startController,
//     required this.endController,
//     required this.onFilter,
//     required this.onRefresh,
//     required this.onStatusChanged,
//     this.selectedStatusVal,
//     required this.formKey,
//     this.isMobile = false,
//     this.dataFrom,
//   });

class DateFilterRow extends ConsumerStatefulWidget {
  final TextEditingController startController;
  final String? selectedStatusVal;
  final String? selectedInsurerVal;
  final String? selectedStaffId;
  final TextEditingController endController;
  final ValueChanged<String?>? onStatusChanged;
  final ValueChanged<String?>? onInsurerChanged;
  final ValueChanged<String?>? onFilterStaff;
  final String? dataFrom;
  final VoidCallback onFilter;
  final VoidCallback onRefresh;
  final GlobalKey<FormState> formKey;
  final bool isMobile;
  final role;
  final id;

  const DateFilterRow({
    super.key,
    required this.startController,
    required this.endController,
    required this.onFilter,
    required this.onRefresh,
    required this.onStatusChanged,
    this.onInsurerChanged,
    this.onFilterStaff,
    required this.selectedStaffId,
    this.selectedStatusVal,
    this.selectedInsurerVal,
    required this.formKey,
    required this.role,
    required this.id,
    this.isMobile = false,
    this.dataFrom,
  });

  @override
  ConsumerState<DateFilterRow> createState() => _DateFilterRowState();
}

class _DateFilterRowState extends ConsumerState<DateFilterRow> {
  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKey =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();
  late ApiService apiService;
  List<Map<String, dynamic>> getStaffDetailsData = [];
  List<Map<String, dynamic>> filteredStaffData = [];
  Map<String, dynamic>? selectedInsurerData;
  List<Map<String, dynamic>> filteredInsurerData = [];
  List<Map<String, dynamic>> getInsurerDetailsData  = [];

  String? selectedInsurer;
  String? selectedStaff;
  String? selectedStaffName;
  dynamic role;
  dynamic managerId;

  bool isLoadingA = false;
  bool isLoading = false;

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

    Future.microtask(() {
      managerId = ref.watch(managerIdProvider);
      final userID = ref.watch(userIdProvider);
      // final handlerId = ref.watch(handlerIdProvider);
      role = ref.watch(userRoleProvider);
      print("managerId - $managerId");
      if (userID != null && role != null) {
        print('hansles');
        getStaffDetails(userID);
      }
      print('***Insurer***');
      getInsurerDetails();
    });

    // Future.microtask(() {
    //   print("CUSTuserID - ${widget.id}, CUSTrole -${widget.role}");
    //   if (widget.role != null && widget.id != null) {
    //     print('hansles');
    //     getStaffDetails(widget.id);
    //   }
    // });
  }

  Future<void> getStaffDetails(int id) async {
    print('getStaffDetails called By handler');
    setState(() {
      isLoading = true;
    });

    try {
      // final response = await apiService.fetchStaffUserList(id, role);
      final response = await apiService.fetchStaffListForEnquiryAssignDropDown(
        managerId,
        id,
        role,
      );
      if (response['status'] == 'success') {
        print('getStaffDetails - ${response['data']}');
        setState(() {
          getStaffDetailsData = List<Map<String, dynamic>>.from(
            response['data'],
          );
          print('API Data - $getStaffDetailsData');

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

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

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

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

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

          filteredInsurerData =
          List<Map<String, dynamic>>.from(getInsurerDetailsData);

          print("Filtered Insurer Data: $filteredInsurerData");
        });
      } else {
        setState(() {
          getInsurerDetailsData = [];
          filteredInsurerData = [];
        });
      }
    } catch (e) {
      print('Error: $e');
    } finally {
      setState(() => isLoadingA = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final spacing = 5.0;

    // final rowChildren = [
    //   buildStartDate(context),
    //   SizedBox(width: spacing),
    //   buildEndDate(context),
    //   SizedBox(width: spacing),
    //   Padding(
    //     padding: const EdgeInsets.symmetric(vertical: 8.0),
    //     child: GestureDetector(
    //       onTap: () {
    //         if (formKey.currentState!.validate()) onFilter();
    //       },
    //       child: Icon(Icons.filter_alt_outlined),
    //     ),
    //   ),
    //   Padding(
    //     padding: const EdgeInsets.all(8.0),
    //     child: GestureDetector(onTap: onRefresh, child: Icon(Icons.refresh)),
    //   ),
    // ];

    List<Widget> getRowChildren(bool isMobile, double spacing) {
      final dateFields = [
        buildStartDate(context),
        SizedBox(width: spacing),
        buildEndDate(context),
        SizedBox(width: spacing),

        if (widget.dataFrom == null && widget.dataFrom != 'Policy') ...[
          buildStatusSearch(context,widget.role),
          SizedBox(width: spacing),
        ],

        if (widget.role == 'manager' || widget.role == 'handler') ...[
          buildSelectStaffMem(context),
          SizedBox(width: spacing),
        ],
          if (widget.role == 'Accounts' && widget.dataFrom == 'Policy') ...[
          buildPolicyReportFlagSearch(context),
          SizedBox(width: spacing),
          buildSelectInsurer(context),
        ],

      ];

      final buttons = [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 0.0),
          // child: GestureDetector(
          //   onTap: () {
          //     if (formKey.currentState!.validate()) onFilter();
          //   },
          //   child: Icon(Icons.filter_alt_outlined),
          // ),
          child: Tooltip(
            message: 'Filter',
            child: IconButton(
              icon: const Icon(
                Icons.search_rounded,
                size: 18,
                color: const Color(0xFF94A3B8),
              ),

              onPressed: () {
                if (widget.formKey.currentState!.validate()) {
                  widget.onFilter();
                }
              },
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(0.0),
          // child: GestureDetector(onTap: onRefresh, child: Icon(Icons.refresh)),
          child: Tooltip(
            message: 'Refresh',
            child: IconButton(
              onPressed: widget.onRefresh,
              icon: const Icon(
                Icons.refresh,
                size: 18,
                color: const Color(0xFF94A3B8),
              ),
            ),
          ),
        ),
      ];

      if (isMobile) {
        // For mobile: buttons below fields
        return [
          ...dateFields,
          SizedBox(height: 10),
          Row(mainAxisAlignment: MainAxisAlignment.end, children: buttons),
        ];
      } else {
        // For desktop: buttons inline with fields
        return [...dateFields, ...buttons];
      }
    }

    return Form(
      key: widget.formKey,
      child: widget.isMobile
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: getRowChildren(widget.isMobile, spacing),
            )
          : Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: getRowChildren(widget.isMobile, spacing),
            ),
    );
  }

  Widget buildStartDate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Text('Start Date', style: _textStyle),
        // SizedBox(height: 5),
        SizedBox(
          height: 35,
          child: ThemedDateField(
            hintText: "Select Date",
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.1,
            // txtheight: 50,
            // backgroundColor: const Color(0xFFECECEC),
            // validator: (value) => Validators.requiredField(value, "date"),
            controller: widget.startController,
            onDateSelected: (date) {
              print("SPicked Date: $date");
              widget.startController.text = DateFormat(
                'dd-MM-yyyy',
              ).format(date);
              //  controllers['date']?.text = date as String;
              // Future.microtask(() => widget.onFilter());
            },
          ),
        ),
      ],
    );
  }

  Widget buildEndDate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Text('End Date', style: _textStyle),
        // SizedBox(height: 5),
        SizedBox(
          height: 35,
          child: ThemedDateField(
            hintText: "Select Date",
            txtwidth: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.1,
            // txtheight: 50,
            // backgroundColor: const Color(0xFFECECEC),
            validator: (value) {
              final fromText = widget.startController.text ?? '';
              if (fromText.isNotEmpty) {
                final startDate = DateFormat('dd-MM-yyyy').parse(fromText);
                if (value == null || value.isEmpty) {
                  return "End Date is required";
                }
                final endDate = DateFormat('dd-MM-yyyy').parse(value);

                if (endDate.isBefore(startDate)) {
                  return "End Date cannot be earlier than Start Date";
                }
              }
              return null; // ✅ no error
            },
            controller: widget.endController,
            lastDate: DateTime.now(),
            onDateSelected: (edate) {
              print("EPicked Date: $edate");
              widget.endController.text = DateFormat('dd-MM-yyyy').format(edate);
              Future.microtask(() => widget.onFilter());
              //  controllers['date']?.text = date as String;
            },
          ),
        ),
      ],
    );
  }

  Widget buildStatusSearch(BuildContext context,role) {

    final List<Map<String, dynamic>> statusOptions;

    if (role == "agent") {
      statusOptions = [
        {'id': 1, 'status': 'Awaiting Proposal'},
        {'id': 2, 'status': 'Proposal Created'},
        {'id': 3, 'status': 'Proposal Accepted'},
        {'id': 4, 'status': 'Proposal Rejected'},
        {'id': 5, 'status': 'Policy Created'},
      ];
    } else {
      statusOptions = [
        {'id': 1, 'status': 'To Be Assigned'},
        {'id': 2, 'status': 'Assigned'},
        {'id': 3, 'status': 'In Progress'},
        {'id': 4, 'status': 'Completed'},
      ];
    }

    Map<String, dynamic>? selectedStatusMap = statusOptions
        .where((element) => element['status'] == widget.selectedStatusVal)
        .cast<Map<String, dynamic>>()
        .toList()
        .firstOrNull;
    Map<String, dynamic>? selectedItem = statusOptions
        .cast<Map<String, dynamic>>()
        .firstWhere(
          (e) => e['status'] == widget.selectedStatusVal,
          orElse: () => {}, // return empty map
        );

    if (selectedItem.isEmpty) selectedItem = null;
    // Map<String, dynamic>? selectedStatus; // ✅ Default: no selection

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Text('Status', style: _textStyle),
        // SizedBox(height: 5),
        SizedBox(
          height: 35,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              border: Border.all(color: Color(0xFFE2E8F0)),
              // color: Colors.black,
            ),
            width: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
            child: DropdownSearch<Map<String, dynamic>>(
              // selectedItem: selectedStatus,
              selectedItem: selectedStatusMap,
              // selectedItem: statusOptions.firstWhere(
              //   (element) => element['status'] == selectedStatusVal,
              //   orElse: () => null, // ✅ return null if not found
              // ),
              items: (filter, infiniteScrollProps) => statusOptions,

              itemAsString: (val) => val['status'].toString(),
              compareFn: (item, selectedItem) =>
                  item['id'] == selectedItem['id'],

              dropdownBuilder: (context, selectedItem) => Align(
                alignment: Alignment.centerLeft,

                child: Text(
                  selectedItem != null ? selectedItem['status'].toString() : "",
                  style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  softWrap: false,
                ),
              ),

              // validator: (val) {
              //   if (val == null) {
              //     return "Please select a status";
              //   }
              //   return null;
              // },
              decoratorProps: DropDownDecoratorProps(
                decoration:
                    AppInputDecorations.dropdownDecoration(
                      label: "Select Status",
                    ).copyWith(
                      filled: true,
                      fillColor: Colors.white,
                      isDense: true, // 👈 reduces built-in vertical padding

                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 1, // 👈 adjust this to make the field shorter
                      ),
                    ),
              ),
              // popupProps: PopupProps.menu(
              //   fit: FlexFit.loose,
              //   constraints: BoxConstraints(maxHeight: 200),
              //   menuProps: MenuProps(backgroundColor: Colors.white),
              //   showSearchBox: false, // 👈 no search box since it's static
              //
              // ),
              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: const BoxConstraints(maxHeight: 200),
                menuProps: const MenuProps(backgroundColor: Colors.white),
                showSearchBox: false,

                itemBuilder: (context, item, isDisabled, isSelected) {
                  // ✅ 4 parameters
                  return Container(
                    // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 6,
                    ),
                    child: Text(
                      item['status'].toString(),
                      style: GoogleFonts.inter(
                        fontSize: 13,
                        color: Colors.black,
                      ),
                    ),
                  );
                },
              ),

              onChanged: (val) {
                if (val != null) {
                  print("Selected Status: ${val['status']}");
                  if (widget.onStatusChanged != null)
                    widget.onStatusChanged!(val['status']);

                  Future.microtask(() => widget.onFilter());
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget buildPolicyReportFlagSearch(BuildContext context) {

    final List<Map<String, dynamic>> policyReportStatusOptions;

    policyReportStatusOptions = [
      {'id': 'Not Verified', 'status': 'Not Verified'},
      {'id': 'Verified', 'status': 'Verified'},
      {'id': 'All', 'status': 'All'},
    ];

    // ✅ If selectedStatusVal is null, fall back based on role
    final String effectiveStatus = widget.selectedStatusVal ??
        (widget.role == 'Accounts' ? 'Not Verified' : 'All');

    Map<String, dynamic>? selectedPolicyReportStatusMap = policyReportStatusOptions
        .where((e) => e['status'] == effectiveStatus)
        .cast<Map<String, dynamic>>()
        .toList()
        .firstOrNull;

    Map<String, dynamic>? selectedItem = policyReportStatusOptions
        .cast<Map<String, dynamic>>()
        .firstWhere(
          (e) => e['status'] == widget.selectedStatusVal,
      orElse: () => {}, // return empty map
    );

    if (selectedItem.isEmpty) selectedItem = null;
    // Map<String, dynamic>? selectedStatus; // ✅ Default: no selection

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Text('Status', style: _textStyle),
        // SizedBox(height: 5),
        SizedBox(
          height: 35,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              border: Border.all(color: Color(0xFFE2E8F0)),
              // color: Colors.black,
            ),
            width: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
            child: DropdownSearch<Map<String, dynamic>>(
              // selectedItem: selectedStatus,
              selectedItem: selectedPolicyReportStatusMap,
              // selectedItem: policyReportStatusOptions.firstWhere(
              //   (element) => element['status'] == selectedStatusVal,
              //   orElse: () => null, // ✅ return null if not found
              // ),
              items: (filter, infiniteScrollProps) => policyReportStatusOptions,

              itemAsString: (val) => val['status'].toString(),
              compareFn: (item, selectedItem) =>
              item['status'] == selectedItem['status'],

              dropdownBuilder: (context, selectedItem) => Align(
                alignment: Alignment.centerLeft,

                child: Text(
                  selectedItem != null ? selectedItem['status'].toString() : "",
                  style: GoogleFonts.poppins(fontSize: 11, color: Colors.black),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  softWrap: false,
                ),
              ),

              // validator: (val) {
              //   if (val == null) {
              //     return "Please select a status";
              //   }
              //   return null;
              // },
              decoratorProps: DropDownDecoratorProps(
                decoration:
                AppInputDecorations.dropdownDecoration(
                  label: "Select Policy Status",
                ).copyWith(
                  filled: true,
                  fillColor: Colors.white,
                  isDense: true, // 👈 reduces built-in vertical padding

                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 1, // 👈 adjust this to make the field shorter
                  ),
                ),
              ),
              // popupProps: PopupProps.menu(
              //   fit: FlexFit.loose,
              //   constraints: BoxConstraints(maxHeight: 200),
              //   menuProps: MenuProps(backgroundColor: Colors.white),
              //   showSearchBox: false, // 👈 no search box since it's static
              //
              // ),
              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: const BoxConstraints(maxHeight: 200),
                menuProps: const MenuProps(backgroundColor: Colors.white),
                showSearchBox: false,

                itemBuilder: (context, item, isDisabled, isSelected) {
                  // ✅ 4 parameters
                  return Container(
                    // color: isSelected ? Colors.blue.withOpacity(0.1) : null,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 6,
                    ),
                    child: Text(
                      item['status'].toString(),
                      style: GoogleFonts.inter(
                        fontSize: 13,
                        color: Colors.black,
                      ),
                    ),
                  );
                },
              ),

              onChanged: (val) {
                if (val != null) {
                  print("Selected Status: ${val['status']}");
                  if (widget.onStatusChanged != null)
                    widget.onStatusChanged!(val['status']);

                  Future.microtask(() => widget.onFilter());
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget buildSelectStaffMem(BuildContext context) {
    // Map<String, dynamic>? selectedVehicle = filteredStaffData.firstWhere(
    //   (item) => item['id'].toString() == selectedStaff,
    //   orElse: () => {},
    // );

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

    Map<String, dynamic>? selectedVehicle;
    if (widget.selectedStaffId == null) {
      selectedVehicle = null;
    } else if (widget.selectedStaffId != null) {
      selectedVehicle = filteredStaffData.firstWhere(
        (item) => item['id'] == widget.selectedStaffId,
        orElse: () => {}, // empty map
      );
      if (selectedVehicle.isEmpty) selectedVehicle = null;
    } else if (selectedStaff != null) {
      selectedVehicle = filteredStaffData.firstWhere(
        (item) => item['id'] == selectedStaff,
        orElse: () => {}, // empty map
      );
      if (selectedVehicle.isEmpty) selectedVehicle = null;
    } else {
      selectedVehicle = null;
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Text("Staff Name", style: _textStyle),
        // SizedBox(height: 10),
        SizedBox(
          height: 35,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              border: Border.all(color: Color(0xFFE2E8F0)),
              // color: Colors.black,
            ),

            width: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.13,
            // height: 45,
            child: DropdownSearch<Map<String, dynamic>>(
              // key: dropDownKey,
              key: ValueKey(selectedStaff),
              // selectedItem: selectedVehicle.isNotEmpty ? selectedVehicle : null,
              selectedItem: selectedVehicle,

              items: (filter, infiniteScrollProps) {
                return filteredStaffData;
              },

              itemAsString: (val) => val['name'].toString(),
              compareFn: (item, selectedItem) =>
                  item['id'] == selectedItem['id'], // ✅ compare by id
              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 Staff ",
                    ).copyWith(
                      filled: true,
                      fillColor:
                          Colors.white, // 👈 makes the dropdown input white
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 1, // 👈 adjust this to make the field shorter
                      ),
                    ),
              ),

              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: BoxConstraints(maxHeight: 250),
                menuProps: MenuProps(
                  backgroundColor:
                      Colors.white, // 👈 sets dropdown background to white
                ),
                showSearchBox: true,
                searchFieldProps: TextFieldProps(
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.white,
                    hintText: "Search 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
                    ),
                  ),
                ),

                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: 13,
                        color: Colors.black,
                      ),
                    ),
                  );
                },

                // constraints: BoxConstraints(),
              ),

              onChanged: (val) {
                if (val != null) {
                  print("Selected Staff : ${val['name']}");
                  print("Id: ${val['id']}");
                  // selectedStaffName = val['name'];
                  // selectedStaff = val['id'];

                  if (widget.onFilterStaff != null)
                    widget.onFilterStaff!(val['id']);

                  Future.microtask(() => widget.onFilter());
                  // controllers['agentId']?.text = val['agent_code'];
                  // agentId = agent['id'];
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget buildSelectInsurer_withoutsearch(BuildContext context) {

    // Ensure this list has data BEFORE building dropdown
    final List<Map<String, dynamic>> insurerOptions =
    List<Map<String, dynamic>>.from(filteredInsurerData);

    // Selected item logic
    Map<String, dynamic>? selectedItem;

    if (widget.selectedInsurerVal != null &&
        widget.selectedInsurerVal.toString().isNotEmpty &&
        insurerOptions.isNotEmpty) {

      try {
        selectedItem = insurerOptions.firstWhere(
              (e) =>
          e['id'].toString() ==
              widget.selectedInsurerVal.toString(),
        );
      } catch (e) {
        selectedItem = null;
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 35,
          child: Container(
            width: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              border: Border.all(color: const Color(0xFFE2E8F0)),
            ),
            child: DropdownSearch<Map<String, dynamic>>(

              selectedItem: selectedItem,

              items: (filter, infiniteScrollProps) => insurerOptions,

              itemAsString: (item) => item['short_name']?.toString() ?? '',

              compareFn: (item, selected) {
                if (selected == null) return false;
                return item['id'].toString() ==
                    selected['id'].toString();
              },

              // FIELD UI
              dropdownBuilder: (context, selectedItem) {
                return Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    selectedItem != null
                        ? selectedItem['short_name'].toString()
                        : '',
                    style: GoogleFonts.poppins(
                      fontSize: 11,
                      color: Colors.black,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                );
              },

              decoratorProps: DropDownDecoratorProps(
                decoration: AppInputDecorations.dropdownDecoration(
                  label: "Select Insurer",
                ).copyWith(
                  filled: true,
                  fillColor: Colors.white,
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 1,
                  ),
                ),
              ),

              // POPUP UI
              popupProps: PopupProps.menu(
                fit: FlexFit.loose,
                constraints: const BoxConstraints(maxHeight: 200),
                menuProps:
                const MenuProps(backgroundColor: Colors.white),
                showSearchBox: false,

                itemBuilder:
                    (context, item, isDisabled, isSelected) {
                  return Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 6,
                    ),
                    child: Text(
                      item['short_name'].toString(),
                      style: GoogleFonts.inter(
                        fontSize: 13,
                        color: Colors.black,
                      ),
                    ),
                  );
                },
              ),

              // ON CHANGE
              onChanged: (val) {
                if (val == null) return;

                selectedInsurer = val['id'];

                widget.onInsurerChanged?.call(val['id']);

                // Safe UI refresh
                Future.microtask(() {
                  widget.onFilter();
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget buildSelectInsurer(BuildContext context) {
    // Ensure this list has data BEFORE building dropdown
    final List<Map<String, dynamic>> insurerOptions =
    List<Map<String, dynamic>>.from(filteredInsurerData);

    // Selected item logic
    Map<String, dynamic>? selectedItem;

    if (widget.selectedInsurerVal != null &&
        widget.selectedInsurerVal.toString().isNotEmpty &&
        insurerOptions.isNotEmpty) {
      try {
        selectedItem = insurerOptions.firstWhere(
              (e) => e['id'].toString() == widget.selectedInsurerVal.toString(),
        );
      } catch (e) {
        selectedItem = null;
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 35,
          child: Container(
            width: ResponsiveLayout.isMobile(context)
                ? null
                : MediaQuery.of(context).size.width * 0.14,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              border: Border.all(color: const Color(0xFFE2E8F0)),
            ),
            child: DropdownSearch<Map<String, dynamic>>(
              selectedItem: selectedItem,

              // FILTER LOGIC: This filters the list as the user types
              items: (filter, infiniteScrollProps) {
                if (filter.isEmpty) {
                  return insurerOptions;
                }
                return insurerOptions
                    .where((item) => item['short_name']
                    .toString()
                    .toLowerCase()
                    .contains(filter.toLowerCase()))
                    .toList();
              },

              itemAsString: (item) => item['short_name']?.toString() ?? '',

              compareFn: (item, selected) {
                if (selected == null) return false;
                return item['id'].toString() == selected['id'].toString();
              },

              // FIELD UI (The collapsed state)
              dropdownBuilder: (context, selectedItem) {
                return Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    selectedItem != null
                        ? selectedItem['short_name'].toString()
                        : '',
                    style: GoogleFonts.poppins(
                      fontSize: 11,
                      color: Colors.black,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                );
              },

              decoratorProps: DropDownDecoratorProps(
                decoration: AppInputDecorations.dropdownDecoration(
                  label: "Select Insurer",
                ).copyWith(
                  filled: true,
                  fillColor: Colors.white,
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 1,
                  ),
                ),
              ),

              // POPUP UI (The expanded state with search)
              popupProps: PopupProps.menu(
                showSearchBox: true, // Enabled searching
                fit: FlexFit.loose,
                constraints: const BoxConstraints(maxHeight: 300),
                menuProps: const MenuProps(backgroundColor: Colors.white),

                // Customizing the search field appearance
                searchFieldProps: TextFieldProps(
                  style: GoogleFonts.poppins(fontSize: 13),
                  decoration: InputDecoration(
                    hintText: "Search insurer...",
                    hintStyle: GoogleFonts.poppins(fontSize: 12),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                  ),
                ),

                itemBuilder: (context, item, isDisabled, isSelected) {
                  return Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      color: isSelected ? Colors.blue.withOpacity(0.1) : Colors.transparent,
                    ),
                    child: Text(
                      item['short_name'].toString(),
                      style: GoogleFonts.inter(
                        fontSize: 13,
                        color: Colors.black,
                      ),
                    ),
                  );
                },
              ),

              // ON CHANGE
              onChanged: (val) {
                if (val == null) return;

                // Note: Ensure 'selectedInsurer' is defined in your state/class
                selectedInsurer = val['id'];

                widget.onInsurerChanged?.call(val['id']);

                // Safe UI refresh
                Future.microtask(() {
                  widget.onFilter();
                });
              },
            ),
          ),
        ),
      ],
    );
  }



  static const _textStyle = TextStyle(
    fontSize: 12,
    fontWeight: FontWeight.w600,
  );

  Widget buildStartDate1() {
    return ThemedDateField(
      controller: widget.startController,
      hintText: 'Select Start Date',
      validator: (value) =>
          value == null || value.isEmpty ? "Start Date required" : null,
      onDateSelected: (date) =>
          widget.startController.text = DateFormat('dd-MM-yyyy').format(date),
    );
  }

  Widget buildEndDate1() {
    return ThemedDateField(
      controller: widget.endController,
      hintText: 'Select End Date',
      lastDate: DateTime.now(),
      validator: (value) {
        if (value == null || value.isEmpty) return "End Date required";

        if (widget.startController.text.isNotEmpty) {
          final start = DateFormat(
            'dd-MM-yyyy',
          ).parse(widget.startController.text);
          final end = DateFormat('dd-MM-yyyy').parse(value);
          if (end.isBefore(start))
            return "End Date cannot be earlier than Start Date";
        }
        return null;
      },
      onDateSelected: (date) =>
          widget.endController.text = DateFormat('dd-MM-yyyy').format(date),
    );
  }
}
