import 'dart:async';
import 'dart:ui';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:nhance_partner/presentation/screens/dashboard/dashboard_nw.dart';
import 'package:nhance_partner/presentation/screens/staff/Enquiry/quotationPopUpAccptReject.dart';
import 'package:nhance_partner/presentation/screens/staff/Enquiry/raise_enq_form.dart';
import 'package:nhance_partner/presentation/screens/staff/Enquiry/staff_policy.dart';
import 'package:nhance_partner/presentation/screens/staff/Enquiry/tabs/tab.dart';
import 'package:nhance_partner/presentation/themes/indicators/customizd_multi_file_upload.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 'package:universal_html/html.dart' as html;

import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../../data/utils/toastNotification.dart'; 
import '../../../../data/utils/validators.dart';
import '../../../layouts/main_layout.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';
import '../../../providers/quotation_staff_proivder.dart';
import '../../../providers/userRoleProvider.dart';
import '../../../themes/indicators/customizd_file_upload.dart';
import '../../../themes/indicators/export_btn.dart';
import '../../../themes/indicators/input_field_decoration.dart';
import '../../../themes/indicators/search_field_theme.dart';

import '../../../widgets/custom_Stdate_EnDate_Filter.dart';
import '../assignStaff.dart';
import 'enquiry_inline_SubRow.dart';
import 'multi_file_list.dart';

class EnquiryListStaffInline extends ConsumerStatefulWidget {

  const EnquiryListStaffInline({super.key});
  @override
  ConsumerState<EnquiryListStaffInline> createState() => EnquiryStaffState();
}

class EnquiryStaffState extends ConsumerState<EnquiryListStaffInline> {
  // bool fromDashboard = false;
  bool _dashboardInitHandled = false;
  bool _resetKeyEnable = false; // very first
  int currentPage = 1;
  int itemsPerPage = 10;

  // int itemsPerPage = 5;

  int completedCurrentPage = 1;

  // int completedItemsPerPage = 5;
  int completedItemsPerPage = 50;
  int totalCompletedPages = 1;
  List<int> itemsPerPageOptions = [25, 50, 100, 200];
  Timer? _debounce;
  late ApiService apiService;
  dynamic userId;
  dynamic idPrimary;
  dynamic managerId;
  dynamic dashboardKey;
  dynamic quickQuotationKey;
  dynamic SelectedStatus;
  dynamic SelectedStaffId;
  String? selectedFileNames;
  String? lastPickedFile;

  PlatformFile? docUploadedFile;
  dynamic handlerId;
  String? _token;
  final _formKey = GlobalKey<FormState>();
  Map<String, String?> fieldErrors = {};

  bool _showEditDrawer = false;

  final raiseEnqKey = GlobalKey<RaiseEnqFormState>();

  // List<Map<String, dynamic>> dataVal = [];
  List<Map<String, dynamic>> getStaffData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];

  List<Map<String, dynamic>> inProgressData = [];
  List<Map<String, dynamic>> completedData = [];

  bool isLoading = false;
  bool isLoadingInsurers = false;
  bool isLoadingInsuranceType = false;
  bool isLoadingBroker = false;
  bool isLoadingPaymentMode = false;
  bool isLoadingStaffEnqAssign = false;
  bool isLoadingStaffList = false;
  bool isLoadingVehicleType = false;
  bool isLoadingAgentList = false;
  dynamic roleId;
  bool _showFilterRow = false;

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

  String formRebuildKey = UniqueKey().toString();

  Map<int, bool> isEditingRow = {};
  Map<int, Map<String, TextEditingController>> rowControllers = {};
  late ProviderSubscription<bool> refreshSub;

  //---------------------- Enquiry TAB Initializations Starts -------------------------------- //

  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 = [];

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

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

  String? selectedVehicleType;
  String? selectedInsurer;
  String? selectedInsPlanType;
  String? selectedAgent;
  PlatformFile? docUploadedRCFile;
  PlatformFile? docUploadedIDProof;
  PlatformFile? docUploadedPrevPolicy;
  String? selectedPaymentMode;

  String? selectedRCFile;
  String? selectedIdProof;
  String? selectedPrevPolicy;

  String? selectedRCFileName;

  String? rcFileUrlFromApi;
  String? idProofFileUrlFromApi;
  String? prevPolicyFileUrlFromApi;

  String? selectedId;

  // int selectedIndex = 1;
  int selectedIndex = 0;
  int autoRefreshIndex = 0;

  final List<String> enquiryTabs = ["In Progress", "Completed"];

  int get fullCompletedCount => completedData.length;

  Map<String, dynamic> dataDetails() {
    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,
      "enquiry_created_on": controllers["enquiry_created_on"]?.text,
      "assigned_to": selectedStaff,
      "insurer_id": selectedInsurer,
      "broker_id": selectedBroker,
      "manager_id": ref.read(managerIdProvider),
      "created_by": userId,
    };

    return data;
  }

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

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

  //---------------------- Assign Staff  starts -------------------------------- //

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

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKeyBroker =
  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;

  final ScrollController _horizontalScrollController = ScrollController();

  // late Timer timer;
  Timer? timer;
  int selectedSeconds = 30;
  bool isActionable = false; // current UI state
  bool userPreference = false; // memory of what the user chose
  bool _listened = false;

  //----------------------  Assign Staff  Ends -------------------------------- //
  //---------------------- Enquiry TAB Initializations Ends -------------------------------- //

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();

  //   if (_dashboardInitHandled) return;
  //   _dashboardInitHandled = true;

  //   final extra = GoRouterState.of(context).extra;

  //   if (extra is Map<String, dynamic>) {
  //     fromDashboard = extra['fromDashboard'] ?? false;
  //   }

  //   // 🔥 IMPORTANT: Clear date pickers ONLY when coming from dashboard
  //   if (fromDashboard) {
  //     controllers['startDate']?.clear();
  //     controllers['endDate']?.clear();
  //   }
  // }

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

    apiService = ApiService();
    // timer = Timer.periodic(Duration(seconds: 10), (Timer t) => callRefresh());   //static

    startTimer();
    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }
    _initializeToken();
    loadPreferences();
    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');
      quickQuotationKey = prefs.getString('QuoteKeyProvider');
      final dashboardStatus = prefs.getString('dashboardStatusProvider');
      final dashboardStaffId = prefs.getString('dashboardStaffIdProvider');

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

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

      if (managerId != null &&
          dashboardKey != null &&
          dashboardStatus != null &&
          dashboardStaffId != null) {
        print("DASHBOARD STATus-$dashboardStatus -- $dashboardStaffId -");
        SelectedStatus = dashboardStatus;
        SelectedStaffId = dashboardStaffId;
        getStaffList(
          managerId,
          roleId,
          SelectedStatus: dashboardStatus,
          SelectedStaffId: dashboardStaffId,
        );
      } else {
        print('ELSE');
        getStaffList(managerId, roleId);
      }

      ref.listen(enquiryRefreshProvider, (prev, next) {
        print('quickQuotationKey1');
        if (next == true) {
          print('quickQuotationKey2 - $next');
          callRefresh();
          ref
              .read(enquiryRefreshProvider.notifier)
              .state = false; // reset
        }
      });
    });

    getPaymentMode();

    refreshSub = ref.listenManual<bool>(enquiryRefreshProvider, (previous,
        next,) {
      if (next == true) {
        print('refresh triggered Quick Creation');
        autoRefrshfilterDateRange();
        // callRefresh();

        ref
            .read(enquiryRefreshProvider.notifier)
            .state = false;
      }
    });
    getInsuranceType();
    getVehicleType();
  }

  // Future<void> loadPreferences() async {
  //   final prefs = await SharedPreferences.getInstance();
  //
  //   setState(() {
  //     isActionable = prefs.getBool('isActionable') ?? false;
  //     selectedSeconds = prefs.getInt('selectedSeconds') ?? 30;
  //
  //     _showFilterRow = true;
  //   });
  //
  //   startTimer(); // restart timer using stored value
  // }
  Future<void> loadPreferences() async {
    final prefs = await SharedPreferences.getInstance();

    setState(() {
      bool savedValue = prefs.getBool('isActionable') ?? false;
      isActionable = savedValue;
      userPreference = savedValue; // Initialize the backup
      selectedSeconds = prefs.getInt('selectedSeconds') ?? 30;

      _showFilterRow = true;
    });

    startTimer(); // restart timer using stored value
  }

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

    await prefs.remove('isActionable');
    await prefs.remove('selectedSeconds');

    setState(() {
      // isActionable = false; // default
      selectedSeconds = 30; // default
    });

    startTimer(); // restart timer with default value

    print("Storage cleared & reset completed");
  }

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

  void startTimer() {
    timer?.cancel(); // stop existing timer

    timer = Timer.periodic(Duration(seconds: selectedSeconds), (Timer t) {
      callRefresh();
    });
  }

  void callRefresh() {
    print('Call Refresh');
    if (!isActionable) {
      print('Call Refresh isActionable');
      autoRefrshfilterDateRange();
    }
  }

  void refresh() {
    final id = ref.read(managerIdProvider);
    final roleId = ref.read(userRoleProvider);
    final userId = ref.read(userIdProvider);

    print("C82 => r : $roleId | mId: $id | uId: $userId ");
    if (managerId != null) {
      getStaffList(managerId, roleId);
    }
  }

  void filterDateRange() {
    // ✅ Call your API
    _searchStaffController.clear();
    getStaffList(
      managerId,
      roleId,
      SelectedStatus: SelectedStatus ?? '',
      SelectedStaffId: SelectedStaffId ?? '',
    );
  }

  @override
  void dispose() {
    refreshSub.close();
    _horizontalScrollController.dispose();
    // ... dispose other controllers ...
    super.dispose();
  }

  // Add this getter method to calculate paginated completed data
  // List<Map<String, dynamic>> get paginatedCompletedData {
  //   if (completedData.isEmpty) return [];
  //
  //   // Calculate total pages
  //   totalCompletedPages = (completedData.length / completedItemsPerPage).ceil();
  //
  //   // Calculate start and end indices
  //   final startIndex = (completedCurrentPage - 1) * completedItemsPerPage;
  //   final endIndex = (startIndex + completedItemsPerPage).clamp(
  //     0,
  //     completedData.length,
  //   );
  //
  //   // Return paginated subset
  //   return completedData.sublist(startIndex, endIndex);
  // }

  List<Map<String, dynamic>> get paginatedCompletedData1 {
    // If search is active (filteredData is different from completedData), use filteredData
    // Otherwise use completedData
    final dataToUse = filteredData;

    print("paginatedCompletedData - $dataToUse");

    if (dataToUse.isEmpty) return [];

    // For completed tab only
    if (selectedIndex == 1) {
      // Calculate total pages based on current data
      totalCompletedPages = (dataToUse.length / completedItemsPerPage).ceil();
      if (totalCompletedPages == 0) totalCompletedPages = 1;

      // Calculate start and end indices
      final startIndex = (completedCurrentPage - 1) * completedItemsPerPage;
      final endIndex = (startIndex + completedItemsPerPage).clamp(
        0,
        dataToUse.length,
      );

      // Return paginated subset
      return dataToUse.sublist(startIndex, endIndex);
    }

    return dataToUse;
  }

  List<Map<String, dynamic>> get paginatedCompletedData {
    final dataToUse = filteredData;

    if (dataToUse.isEmpty) return [];

    if (selectedIndex == 1) {
      totalCompletedPages = (dataToUse.length / completedItemsPerPage)
          .ceil()
          .clamp(1, double.infinity)
          .toInt();

      final startIndex = (completedCurrentPage - 1) * completedItemsPerPage;

      // 🚨 Guard: page out of range after search
      if (startIndex >= dataToUse.length) {
        completedCurrentPage = 1;
        return dataToUse.take(completedItemsPerPage).toList();
      }

      final endIndex = (startIndex + completedItemsPerPage).clamp(
        0,
        dataToUse.length,
      );

      return dataToUse.sublist(startIndex, endIndex);
    }

    return dataToUse;
  }

  Future<void> autoRefrshfilterDateRange() async {
    print('autorefrshfilterDateRange');
    // setState(() async {
    final prefs = await SharedPreferences.getInstance();

    // _formKey.currentState?.reset();

    final int parsedManagerId = int.tryParse(managerId.toString()) ?? 0;
    print('autorefrshfilterDateRange 1');
    getStaffList(
      // managerId,
      parsedManagerId,
      roleId,
      SelectedStatus: SelectedStatus ?? '',
      SelectedStaffId: SelectedStaffId ?? '',
    );
    autoRefreshIndex = selectedIndex;
    print('autoRefreshIndex - $autoRefreshIndex');
    _searchStaffController.clear();
    print('refrshfilterDateRange 2');
  }

  Future<void> refrshfilterDateRange() async {
    setState(() {
      _resetKeyEnable = true;
    });
    _searchStaffController.clear();
    print('refrshfilterDateRange');
    // setState(() async {
    final prefs = await SharedPreferences.getInstance();

    // ✅ Clear any old data
    await prefs.remove('dashboardKeyProvider');
    await prefs.remove('dashboardStatusProvider');
    await prefs.remove('dashboardStaffIdProvider');
    SelectedStatus = '';
    SelectedStaffId = null;
    controllers['startDate']!.clear();
    controllers['endDate']!.clear();

    controllers['startDate']?.text = '';
    controllers['endDate']?.text = '';
    // Reset the FormField validation
    _formKey.currentState?.reset();
    // });

    final int parsedManagerId = int.tryParse(managerId.toString()) ?? 0;
    print('refrshfilterDateRange 1');
    getStaffList(
      // managerId,
      parsedManagerId,
      roleId,
      SelectedStatus: SelectedStatus ?? '',
      SelectedStaffId: SelectedStaffId ?? '',
    );
    print('refrshfilterDateRange 2');
  }

  Future<void> getPaymentMode() async {
    print('getPaymentMode called');
    setState(() {
      isLoadingPaymentMode = 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(() {
        isLoadingPaymentMode = false;
      });
    }
  }

  Future<void> getInsuranceType() async {
    print('getClaimList called');
    setState(() {
      isLoadingInsuranceType = 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(() {
        isLoadingInsuranceType = false;
      });
    }
  }

  Future<void> getVehicleType() async {
    print('EIL 1getVT-called');
    setState(() {
      isLoadingVehicleType = true;
    });

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

      if (response['status'] == 200) {
        print('EIL 2getVT-Data - ${response['data']}');
        setState(() {
          getVehicleTypeData = List<Map<String, dynamic>>.from(response['data']);
          // getVehicleTypeData = List<Map<String, dynamic>>.from(response['data']).where((item) => item['is_active']?.toString() == '1').toList();

          // print('EIL 3getVT-B4filterData : $getVehicleTypeData');
          filteredVehicleData = List.from(getVehicleTypeData);
          // print('EIL 3getVT-AftfilterData : $filteredVehicleData');
        });
      } else {
        getVehicleTypeData = [];
        filteredVehicleData = [];
      }
    } catch (e) {
      print('EIL 2getVT-Exception occurred: $e');
    } finally {
      setState(() {
        isLoadingVehicleType = false;
      });
    }
  }

  Future<void> getStaffList(int managerId,
      role, {
        String fromDate = '',
        String toDate = '',
        String SelectedStatus = '',
        String SelectedStaffId = '',
      }) async {
    print('A613 => Fns called => $managerId | $role');
    setState(() {
      isLoadingStaffList = true;
    });
    print('A713 => Fns called => $managerId | $role');

    dynamic fromDt;
    dynamic toDt;

    final fromDateVal = controllers['startDate']?.text ?? '';
    final toDateVal = controllers['endDate']?.text ?? '';
    final dateFormat = DateFormat('dd-MM-yyyy');

    if (dashboardKey == 'fromDashboard' && SelectedStatus == "PrevPending") {
      setState(() {
        _dashboardInitHandled = true;
      });
      final today = DateTime.now();
      final DateTime yesterday = today.subtract(const Duration(days: 1));
      final DateTime fromDate = DateTime(2025, 10, 1); // hardcoded Date
      controllers['startDate']?.text = dateFormat.format(fromDate);
      controllers['endDate']?.text = dateFormat.format(yesterday);
      print('UnA813 => Fns called => $managerId | $role');

      // For PREV PENDING → set date range until yesterday
      // Change to dd-MM-yyyy
      // final dateFormat = DateFormat('dd-MM-yyyy');
      // final yesterday = today.subtract(Duration(days: 1));

      fromDt = _dashboardInitHandled ? controllers['startDate']?.text : '';
      toDt = _dashboardInitHandled ? controllers['endDate']?.text : '';
      // fromDt = dateFormat.format(yesterday.subtract(Duration(days: 15)));
      // toDt = dateFormat.format(yesterday);

      print('PrevPending FROM TO - $fromDt - $toDt');
    } else if (dashboardKey == 'fromDashboard' &&
        SelectedStatus != "PrevPending" &&
        SelectedStatus != '') {
      // For PREV PENDING → set date range until yesterday
      final today = DateTime.now();
      print('A913 => Fns called => $managerId | $role');
      // Change to dd-MM-yyyy
      final dateFormat = DateFormat('dd-MM-yyyy');

      // fromDt = dateFormat.format(today);
      // toDt = dateFormat.format(today);

      fromDt = _dashboardInitHandled ? controllers['startDate']?.text : '';
      toDt = _dashboardInitHandled ? controllers['endDate']?.text : '';
      print('End Date: ${controllers['endDate']?.text}');
      print('STT Date: ${controllers['startDate']?.text}');

      print('PrevPending FROM TO - $fromDt - $toDt');
    } else if (dashboardKey != 'fromDashboard' &&
        fromDateVal == '' &&
        toDateVal == '') {
      print("ENQ LIST PAGE");
      print('A1013 => Fns called => $managerId | $role');

      final today = DateTime.now();
      fromDt = dateFormat.format(today.subtract(Duration(days: 4)));
      // fromDt = dateFormat.format(today);
      toDt = dateFormat.format(today);

      print('Enq FROM TO - $fromDt - $toDt');
    } else {
      print('A1113 => Fns called => $managerId | $role');
      print('Pre Date its User Choosen Enq Inline list - $fromDt - $toDt');

      if (_resetKeyEnable) {
        print('A12131 => Fns called => $managerId | $role');
        final dateFormat = DateFormat('dd-MM-yyyy');
        final today = DateTime.now();
        // final yesterday = today.subtract(Duration(days: 1));
        // fromDt = dateFormat.format(yesterday.subtract(Duration(days: 15))); // Dont Delete any doubt Ref Suren
        fromDt = dateFormat.format(today.subtract(const Duration(days: 4)));
        toDt = dateFormat.format(today);

        setState(() {
          controllers['startDate']?.text = fromDt;
          controllers['endDate']?.text = toDt;
          _resetKeyEnable = false; // ask suren Never forgot
        });
      } else {
        print('A13131 => Fns called => $managerId | $role');
        fromDt = fromDateVal;
        toDt = toDateVal;
      }
    }
    print('Enq 2- $fromDt - $toDt');
    String finalStatus = SelectedStatus;
    print('finalStatus1 - $finalStatus');

    print('A1213 => Fns called => $managerId | $role');

    try {
      final response = await apiService.fetchEnquiryList(
        managerId,
        userId,
        role,
        fromDate: _dashboardInitHandled
            ? controllers['startDate']?.text
            : fromDt,
        toDate: _dashboardInitHandled ? controllers['endDate']?.text : toDt,
        // selectedStatus: (finalStatus != '' && finalStatus != 'PrevPending')
        //     ? finalStatus
        //     : '',
        selectedStatus:
        (SelectedStatus != '' && SelectedStatus != 'PrevPending')
            ? SelectedStatus
            : '',
        selectedStaffId: SelectedStaffId ?? '',
      );

      if (response['status'] == 'success') {
        final data = response['data'];
        final fromDate = response['from_date'] ?? '';
        final toDate = response['to_date'] ?? '';

        print('FromDate : $fromDate');
        print('ToDate : $toDate');
        print('A1213 => Fns called => $managerId | $role');

        setState(() {
          _resetKeyEnable = false;

          controllers['startDate']?.text = fromDate;
          controllers['endDate']?.text = toDate;


          if (data is List) {
            getStaffData = List<Map<String, dynamic>>.from(data);

            originalData = List<Map<String, dynamic>>.from(data);

            // Split data immediately after fetching
            inProgressData = originalData
                .where((item) => item['enquiry_status'] != 'Completed')
                .toList();

            print('inProgressData - $inProgressData');

            completedData = originalData
                .where((item) => item['enquiry_status'] == 'Completed')
                .toList();
            print('completedData - $completedData');

            // filteredData now holds the currently displayed tab's data (without search)
            // filteredData = (selectedIndex == 0)
            //     ? inProgressData
            //     : completedData;

            // 👇 IMPORTANT: Set filteredData based on current tab
            filteredData = (selectedIndex == 0)
                ? List.from(inProgressData)
                : List.from(completedData);

            if (SelectedStatus == 'Completed') {
              selectedIndex = 1;
            }

            print('filteredData count: ${filteredData.length}');
            print('inProgressData count: ${inProgressData.length}');
            print('completedData count: ${completedData.length}');
          } else if (data is Map) {
            getStaffData = [Map<String, dynamic>.from(data)];
          } else {
            getStaffData = [];
          }
          originalData = getStaffData;
          filteredData = List.from(originalData);
        });
      } else {
        getStaffData = [];
        originalData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoadingStaffList = false;
      });
    }
  }

  String safeString(dynamic value) {
    if (value == null) return '';
    return value.toString();
  }

  void filterData(String query) {
    _debounce?.cancel();
    _debounce = Timer(const Duration(milliseconds: 300), () {
      _applyFilter(query);
    });
  }

  void _applyFilter(String query) {
    setState(() {
      final List<dynamic> source =
      (selectedIndex == 0) ? inProgressData : completedData;

      final String q = query.trim().toLowerCase();
      completedCurrentPage = 1;

      // Reset filter
      if (q.length < 2) {
        filteredData = List<Map<String, dynamic>>.from(source);
        return;
      }

      final List<Map<String, dynamic>> results = source.where((item) {
        final map = item as Map<String, dynamic>;
        final String regNo = safeString(map['reg_no']).toLowerCase().trim();
        final String agentName = safeString(map['agent_name']).toLowerCase().trim();
        if (q == 'new') { return regNo == 'new' || agentName == 'new'; }
        // All searchable fields
        final values = [
          regNo,
          agentName,
          _s(map['agent_code']),
          _s(map['assigned_to_name']),
          _s(map['insured_name']),
          _s(map['insurer_short_name']),
          _s(map['broker_name']),
          _s(map['payment_mode_value']),
          _s(map['vehicle_type']),
          _s(map['enquiry_status']),
          _s(map['insurance_plan_type']),
          _s(map['status']),
          _s(_formatDate(map['enquiry_created_on'])),
          // _s(_formatDate(map['created_on'])),
          _s(_formatDate(map['updated_on'])),
        ];

        return values.any((v) => v.contains(q));
      }).cast<Map<String, dynamic>>().toList();

      filteredData = results;
    });
  }

  String _s(dynamic v) => (v ?? '').toString().toLowerCase().trim();

  void _applyFilter_06012026(String query) {
    setState(() {
      final List<dynamic> source = (selectedIndex == 0)
          ? inProgressData
          : completedData;
      final String q = query.trim().toLowerCase();
      completedCurrentPage = 1;

      if (q.length < 2) {
        filteredData = List<Map<String, dynamic>>.from(source);
        return;
      }

      // 1. Filter the list
      List<dynamic> results = source.where((item) {
        final map = item as Map<String, dynamic>;

        // Get the field values safely
        String regNo = safeString(map['reg_no']).toLowerCase().trim();
        String agentName = safeString(map['agent_name']).toLowerCase().trim();

        // IF CONDITION: Check if query is exactly "new"
        if (q == "new") {
          // Only return items where the field is EXACTLY "new"
          return regNo == "new" || agentName == "new";
        } else {
          // Regular partial search for any other query
          return regNo.contains(q) || agentName.contains(q);
        }
      }).toList();

      // 2. Final Type Casting to fix your "dynamic" error
      filteredData = results.map((e) => e as Map<String, dynamic>).toList();
    });
  }

  void _applyFilter_05012026(String query) {
    print("FilterData - $query");

    setState(() {
      final sourceList = (selectedIndex == 0) ? inProgressData : completedData;

      final q = query.trim().toLowerCase();

      completedCurrentPage = 1;

      if (q.length < 2) {
        filteredData = List.from(sourceList);
        return;
      }

      filteredData = sourceList.where((item) {
        return safeString(item['agent_name']).toLowerCase().contains(q) ||
            safeString(item['agent_code']).toLowerCase().contains(q) ||
            safeString(item['reg_no']).toLowerCase().contains(q) ||
            safeString(item['insured_name']).toLowerCase().contains(q) ||
            safeString(item['policy_number']).toLowerCase().contains(q) ||
            safeString(item['broker_name']).toLowerCase().contains(q) ||
            safeString(item['insurer_name']).toLowerCase().contains(q) ||
            safeString(item['insurer_short_name']).toLowerCase().contains(q) ||
            safeString(item['enquiry_status']).toLowerCase().contains(q) ||
            safeString(item['assigned_to_name']).toLowerCase().contains(q) ||
            safeString(item['status']).toLowerCase().contains(q) ||
            safeString(item['payment_mode']).toLowerCase().contains(q) ||
            safeString(item['premium_amount']).toLowerCase().contains(q) ||
            (q.contains('proceed') &&
                item['enquiry_status']?.toLowerCase() == 'assigned' &&
                item['quotation_id'] != null) ||
            safeString(
              _formatDate(item['enquiry_created_on']),
            ).toLowerCase().contains(q) ||
            // safeString(
            //   _formatDate(item['created_on']),
            // ).toLowerCase().contains(q) ||
            safeString(
              _formatDate(item['updated_on']),
            ).toLowerCase().contains(q);
      }).toList();

      print("FilterData2 - ${filteredData.length}");
    });
  }

  // void _applyFilter(String query) {
  //   print("FilterData - $query");
  //   setState(() {
  //     // ALWAYS search from the FULL source list, not current filtered results
  //     final sourceList = (selectedIndex == 0) ? inProgressData : completedData;
  //
  //     final q = query.trim().toLowerCase();
  //
  //     if (q.length < 2) {
  //       filteredData = List.from(sourceList);
  //       return;
  //     }
  //
  //     if (query.isEmpty) {
  //       // If search is empty, show all data for current tab
  //       filteredData = List.from(sourceList);
  //
  //       print("FilterData1 - $filteredData");
  //     } else {
  //       // Search within ALL data from the current tab's source
  //       filteredData = sourceList.where((item) {
  //         final searchLower = query.toLowerCase();
  //
  //         return safeString(
  //               item['agent_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['agent_code'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(item['reg_no']).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['insurer_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['enquiry_status'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['assigned_to_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['insured_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['insurer_short_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['premium_amount']?.toString(),
  //             ).contains(searchLower) ||
  //             safeString(
  //               item['payment_mode'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               item['broker_name'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(
  //               _formatDate(item['created_on']),
  //             ).toLowerCase().contains(q) ||
  //             safeString(
  //               _formatDate(item['updated_on']),
  //             ).toLowerCase().contains(q) ||
  //             safeString(
  //               item['policy_number'],
  //             ).toLowerCase().contains(searchLower) ||
  //             safeString(item['status']).toLowerCase().contains(searchLower);
  //
  //         // return safeString(
  //         //       item['agent_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['agent_code'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['reg_no'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['insurer_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['enquiry_status'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['assigned_to_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['insured_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['insurer_short_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['premium_amount'] ?? '-',
  //         //     ).toString().toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['payment_mode'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['broker_name'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       _formatDate(item['created_on']),
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       _formatDate(item['updated_on']),
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['policy_number'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower) ||
  //         //     safeString(
  //         //       item['status'] ?? '-',
  //         //     ).toLowerCase().contains(searchLower);
  //       }).toList();
  //       print("FilterData2 - $filteredData");
  //       // Reset to page 1 when searching in completed tab
  //       if (selectedIndex == 1) {
  //         completedCurrentPage = 1;
  //       }
  //     }
  //   });
  // }

  void filterData1(String query) {
    print("FilterData - $query");
    setState(() {
      // Get the correct source list based on selected tab
      final sourceList = (selectedIndex == 0) ? inProgressData : completedData;

      if (query.isEmpty) {
        // If search is empty, show all data for current tab
        filteredData = List.from(sourceList);
      } else {
        // Search within the current tab's data
        filteredData = sourceList.where((item) {
          return (item['agent_name'] ?? '-').toLowerCase().contains(
            query.toLowerCase(),
          ) ||
              (item['agent_code'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['reg_no'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['insurer_name'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['enquiry_status'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['assigned_to_name'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['insured_name'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['insurer_short_name'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['premium_amount'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['payment_mode'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['broker_name'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (_formatDate(item['enquiry_created_on']) ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              // (_formatDate(item['created_on']) ?? '-').toLowerCase().contains(
              //   query.toLowerCase(),
              // ) ||
              (_formatDate(item['updated_on']) ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['policy_number'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              ) ||
              (item['status'] ?? '-').toLowerCase().contains(
                query.toLowerCase(),
              );
        }).toList();
      }

      if (selectedIndex == 1) {
        completedCurrentPage = 1;
      }
    });
  }

  final TextEditingController _searchStaffController = TextEditingController();

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

  Future<void> handleStaff(BuildContext context,
      dynamic data,
      id,
      regNum,) async {
    showDialog(
      context: context,
      builder: (ctx) =>
          AssignStaffDialog(
            enquiryPrimaryId: id,
            regNum: regNum,
            userId: userId,
            onSubmit: (value) {
              debugPrint("New assignY: $value");
              refresh();
            },
          ),
    );
  }

  Future<void> handleProposalAccept(BuildContext context, String id) async {
    final result = showDialog(
      context: context,
      barrierDismissible: true, // allows tapping outside to close
      builder: (ctx) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(26),
          ),
          insetPadding: const EdgeInsets.all(24),
          child: Container(
            width: 500,
            height: 300,
            color: Colors.white,
            child: QuotationPopUpTab(id: id, onRefresh: refrshfilterDateRange),
          ),
        );
      },
    );

    print("Dialog result: $result");
    ();
  }

  Future<void> handleDeleteEnq(Map<String, dynamic> item) async {
    final id = int.tryParse(item['id'].toString()) ?? 0;

    // Note: Avoid setting idPrimary here if you are just deleting,
    // unless your UI specifically needs to highlight it.
    idPrimary = item['id'];

    print("handleDeleteEnq - $idPrimary");
    final res = await apiService.deleteEnquiy(id, 0);

    if (res['status'] == 'success') {
      // RESET THE ID HERE
      setState(() {
        idPrimary = null;
        selectedId = null;
        isEditingRow[id] = false;
      });

      autoRefrshfilterDateRange();
    }
  }

  void handleEdit(Map<String, dynamic> item) {
    print("handleEdit");

    final id = int.tryParse(item['id'].toString()) ?? 0;
    idPrimary = item['id'];

    print("handleEdit - $idPrimary");
    setState(() {
      selectedId = idPrimary;
      isEditingRow[id] = true;
    });
    for (final field in tabHeader) {
      // Only set if controller exists
      if (controllers.containsKey(field)) {
        controllers[field]!.text = item[field] != null
            ? item[field].toString()
            : ''; // fallback to empty string
      }
    }

    //dropdowns or IDs
    selectedVehicleType = item['vehicle_type_id'];
    selectedAgent = item['agent_id'];
    managerId = item['manager_id'];
    controllers["regNo"]?.text = item['reg_no'];
    controllers["remarks"]?.text = item['remarks'];
    controllers["enquiry_created_on"]?.text = item['enquiry_created_on'];

    selectedInsurer = item['insurer_id'];
    selectedStaff = item['assigned_to'];
    selectedBroker = item['broker_id'];
    setState(() {});
  }

  Future<void> handlePaymentMode(id, quotId) async {
    Map<String, dynamic> data = {
      "quotation_id": quotId,
      "payment_mode_id": id,
      "updated_by": userId,
    };

    final path = 'quotation/updateQuoteData';

    final res = await apiService.createUserData(data, path);

    print("handlePaymentMode - $res");

    if (res['status'] == 'success') {
      print("handlePaymentModesuccess");
      refrshfilterDateRange();
    }
  }

  Future<void> handleInsurancePlanTypeMode(id, quotId) async {
    Map<String, dynamic> data = {
      "quotation_id": quotId,
      "insurance_plan_type_id": id,
      "updated_by": userId,
    };

    final path = 'quotation/updateQuoteData';

    final res = await apiService.createUserData(data, path);
    print("handleINSMode - $res");
    if (res['status'] == 'success') {
      print("handleINSsuccess");
      refrshfilterDateRange();
    }
  }

  Future<void> handleVehicleType(VtId, EId) async {
    print('EIL 1handleVT-called');
    print('EIL 2handleVT-vtid  ${VtId}');
    print('EIL 3handleVT-eid  ${EId}');
    Map<String, dynamic> data = {
      "id": EId,
      "vehicle_type_id": VtId,
      "updated_by": userId,
    };

    final path = 'enquiry/setVehicleTypeToEnquiry';

    final res = await apiService.createUserData(data, path);
    print('EIL 4handleVT-res  $res');
    if (res['status'] == 'success') {
      print('EIL 5handleVT-res  ${res['status']}');
      refrshfilterDateRange();
    }
  }

  void handleSave(dynamic id) {
    print('#enquiry SAVE -- $id');
    // final ids = int.tryParse(id.toString()) ?? 0;

    idPrimary = id;
    handleEnqTabSave();

    setState(() => rowExpanded.clear());
  }

  void handleCancel(int id) {
    print('handleCancel id - $id');

    final bool isNewRow =
        int.tryParse(id.toString()) != null &&
            int.parse(id.toString()) > 1000000000000;

    print('isNewRow - $isNewRow');

    setState(() {
      if (isNewRow) {
        // Check if this is a new unsaved row
        final row = getStaffData.firstWhere(
              (item) => item['id'].toString() == id.toString(),
          orElse: () => {},
        );

        // If policy_number is empty, it's a new row - remove it
        if (row.isNotEmpty) {
          getStaffData.removeWhere(
                (item) => item['id'].toString() == id.toString(),
          );
          originalData.removeWhere(
                (item) => item['id'].toString() == id.toString(),
          );
          filteredData.removeWhere(
                (item) => item['id'].toString() == id.toString(),
          );
          rowControllers.remove(id);
        }
      }

      // Turn off editing mode
      isEditingRow.remove(id);
    });
  }

  //---------------------- Enquiry TAB Logins Starts -------------------------------- //

  Map<String, dynamic> dataEnquiryTabDetails() {
    final data = {
      "agent_id": ((roleId == 'handler') || (roleId == 'manager'))
          ? 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',
      // "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,
      "enquiry_created_on" : controllers["enquiry_created_on"]?.text,
      "manager_id": managerId,
      "created_by": userId,
    };

    return data;
  }

  // Update validation method to set errors
  bool _validateRequiredFields() {
    setState(() {
      fieldErrors.clear(); // Clear previous errors

      // Validate Partner/Agent
      if (selectedAgent == null || selectedAgent == '') {
        fieldErrors['agent'] = 'Partner is required';
      }

      // Validate Insured Name
      if (controllers['name']?.text
          .trim()
          .isEmpty ?? true) {
        fieldErrors['name'] = 'Insured Name is required';
      }

      // Validate Vehicle Number
      if (controllers['regNo']?.text
          .trim()
          .isEmpty ?? true) {
        fieldErrors['regNo'] = 'Vehicle Number is required';
      }

      // Validate Vehicle Type
      if (selectedVehicleType == null || selectedVehicleType == '') {
        fieldErrors['vehicleType'] = 'Vehicle Type is required';
      }

      // Validate email format if provided
      final email = controllers['email']?.text.trim() ?? '';
      if (email.isNotEmpty) {
        final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
        if (!emailRegex.hasMatch(email)) {
          fieldErrors['email'] = 'Invalid email format';
        }
      }

      // Validate mobile number if provided
      final mobile = controllers['mobile']?.text.trim() ?? '';
      if (mobile.isNotEmpty) {
        final cleanMobile = mobile.replaceAll(' ', '');
        if (cleanMobile.length < 10) {
          fieldErrors['mobile'] = 'Must be at least 10 digits';
        }
      }
    });

    return true;

    return fieldErrors.isEmpty;
  }

  Future<void> handleEnqTabSave() async {
    if (!_validateRequiredFields()) return;

    // setState(() {
    //   isSaving = true; // start saving
    // });

    final dataSet = dataDetails();

    try {
      await createUserData(dataSet); // API call

      // ToastHelper.showInfoToast(context, "Enquiry saved successfully");
    } catch (e) {
      showDialog(
        context: context,
        builder: (_) =>
            AlertDialog(
              title: const Text('Error'),
              content: Text(e.toString()),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('OK'),
                ),
              ],
            ),
      );
    } finally {
      // setState(() => isSaving = false); // re-enable button after save
    }
  }

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

    await addFileOrKeepName(
      docUploadedRCFile,
      rcFileUrlFromApi,
      'rc_file_name',
    );
    await addFileOrKeepName(
      docUploadedIDProof,
      idProofFileUrlFromApi,
      'id_proof_file_name',
    );
    await addFileOrKeepName(
      docUploadedPrevPolicy,
      prevPolicyFileUrlFromApi,
      'previous_policy_file_name',
    );
  }

  Future<void> createUserData(Map<String, dynamic> userData) async {

    print('#enquiry userData: $userData ');

    final bool isNewRow =
        idPrimary != null &&
            int.tryParse(idPrimary.toString()) != null &&
            int.parse(idPrimary.toString()) > 1000000000000;

    final bool isUpdating =
        idPrimary != null && idPrimary != 'null' && !isNewRow;


    // final bool isUpdating = idPrimary != 'null';
    final id = idPrimary;

    // final bool isUpdating = false;
    final uri = Uri.parse(
      isUpdating
          ? '${Env.apiUrl}enquiry/updateEnquiry'
          : '${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;

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


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

    // attach files

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

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

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

      if (response.statusCode == 200 || response.statusCode == 201) {
        // dispose();
        print("✅ Enquiry submitted successfully!");
        ToastHelper.showSuccessToast(context, 'Saved Enquiry');
        print("Response: ${response.body}");
        // Clear the temporary ID
        idPrimary = null;
        refrshfilterDateRange();
        // getStaffList(managerId, roleId);
        // setState(() => isSaving = false);
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      } else {
        print("❌ Submission failed. Status: ${response.statusCode}");
        print("Body: ${response.body}");

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

  Future<void> uploadPolicyPDF({
    required Map<String, dynamic> data,
    required PlatformFile? file,
  }) async {
    if (_token == null) throw Exception("Token missing. Please login.");

    final uri = Uri.parse('${Env.apiUrl}policy/uploadPolicyFile');
    final request = http.MultipartRequest('POST', uri);

    request.headers['Authorization'] = 'Bearer $_token';
    request.headers['app-signature'] = Env.App_Signature;

    print("🔥 Upload Request Data: $data");

    // 1️⃣ Add text fields (except file)
    data.forEach((key, value) {
      if (value != null && key != 'policy_pdf_file_name') {
        request.fields[key] = value.toString();
        print("➡️ Field Added: $key = ${request.fields[key]}");
      }
    });

    // 2️⃣ Attach file
    if (file != null) {
      if (file.bytes != null) {
        request.files.add(
          http.MultipartFile.fromBytes(
            'policy_pdf_file_name',
            file.bytes!,
            filename: file.name,
          ),
        );
      } else if (file.path != null) {
        request.files.add(
          await http.MultipartFile.fromPath(
            'policy_pdf_file_name',
            file.path!,
            filename: file.name,
          ),
        );
      }
      print("📎 File attached: ${file.name}");
    } else {
      print("⚠️ No file selected!");
    }

    // Submit request
    try {
      final response = await http.Response.fromStream(await request.send());

      print("📥 Response Code: ${response.statusCode}");
      print("📥 Response Body: ${response.body}");

      if (response.statusCode == 200 || response.statusCode == 201) {
        ToastHelper.showSuccessToast(context, "Policy PDF Uploaded!");
        setState(() {
          docUploadedFile = null;
        });
        refrshfilterDateRange();
        setState(() {});
        return;
      }

      if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
        return;
      }

      ToastHelper.showErrorToast(context, "Upload failed!");
    } catch (e) {
      print("❌ Error uploading file: $e");
    }
  }

  //---------------------- Enquiry TAB Logins End -------------------------------- //
  @override
  Widget build(BuildContext context) {
    return MainLayout(
      title: "Enquiries",
      body: SelectionArea( child: Container(
        width: MediaQuery
            .of(context)
            .size
            .width,
        // height: MediaQuery.of(context).size.height * 0.1,
        // padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              // height: MediaQuery.of(context).size.height*0.
              child: RaiseEnqForm(
                // key: raiseEnqKey,
                key: ValueKey(formRebuildKey),
                onSubmit: (dataSet) async {
                  print('Check checking dataSet $dataSet');
                  try {
                    await createUserData(dataSet); // <-- API call here
                    print("Enquiry saved successfully");
                    // RESET FORM
                    raiseEnqKey.currentState?.resetFormFields();
                    // REBUILD THE ENTIRE FORM
                    setState(() {
                      formRebuildKey = UniqueKey().toString();
                    });
                  } catch (e) {
                    showDialog(
                      context: context,
                      builder: (_) =>
                          AlertDialog(
                            title: const Text('Error'),
                            content: Text(e.toString()),
                            actions: [
                              TextButton(
                                onPressed: () => Navigator.of(context).pop(),
                                child: const Text('OK'),
                              ),
                            ],
                          ),
                    );
                  }
                },
              ),
            ),

            // SizedBox(height: 5),
            ResponsiveLayout.isMobile(context)
                ? Container(
              height: MediaQuery
                  .of(context)
                  .size
                  .height * 0.69,
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(2),
                  child: _buildContent(context),
                ),
              ),
            )
                :
            // Expanded(
            //         child:
            Container(
              width: MediaQuery
                  .of(context)
                  .size
                  .width,
              height: MediaQuery
                  .of(context)
                  .size
                  .height * 0.69,
              // padding: EdgeInsets.symmetric(
              //   horizontal: 8.0,
              //   vertical: 2.0,
              // ),
              child: _buildContent(context),
            ),
          ],
        ),
      ), )
    );
  }

  Future<void> buildStatusActions(BuildContext context, status, id) async {
    print("Actionsstatus - $status -$id");
    dynamic val;
    if (status == 'Awaiting Proposal' || status == 'Proposal Created') {
      val = '';
    } else {
      val = 'Policy';
    }

    final result = await showDialog(
      context: context,
      barrierDismissible:
      false, // optional - prevents closing by tapping outside
      builder: (context) => TabEnquiryStaffList(showKey: val),
    );

    // ✅ Code here runs *after* the dialog is closed
    print("Dialog closed");
    print("Dialog result: $result");
    refrshfilterDateRange();
  }

  Future<void> buildPolicyCreatedStatusActions(BuildContext context,
      status,
      id,) async {
    print("Actionsstatus - $status -$id");
    dynamic val;
    if (status == 'Awaiting Proposal' || status == 'Proposal Created') {
      val = '';
    } else {
      val = 'Policy';
    }

    final result = await showDialog(
      context: context,
      barrierDismissible:
      false, // optional - prevents closing by tapping outside
      builder: (context) => PolicyStaffEnqList(),
    );

    // ✅ Code here runs *after* the dialog is closed
    print("Dialog closed");
    print("Dialog result: $result");
    if (result) {
      refrshfilterDateRange();
    }
  }

  Widget _buildContent(BuildContext context) {
    final isDesktop = !ResponsiveLayout.isMobile(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 10),
        Container(
          // height: 40,
          // color: Color(0xffF1F5F9),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              if (_showFilterRow) ...[
                DateFilterRow(
                  formKey: _formKey,
                  // key: ValueKey(SelectedStatus ?? ''),
                  role: roleId,
                  id: userId,
                  selectedStatusVal: SelectedStatus,
                  selectedStaffId: SelectedStaffId,
                  onFilterStaff: (val) {
                    print('Selected Filterd STAFF Id - $val');
                    SelectedStaffId = val;
                  },
                  // selectedStaffId: SelectedStaffId,
                  startController: controllers['startDate']!,
                  endController: controllers['endDate']!,
                  onStatusChanged: (val) {
                    SelectedStatus = val; // update parent
                  },

                  isMobile: ResponsiveLayout.isMobile(context),
                  onFilter: () {
                    // call your filter logic
                    filterDateRange();
                  },
                  onRefresh: () {
                    // call your refresh logic
                    refrshfilterDateRange();
                  },
                ),
              ],
              IconButton(
                icon: Icon(
                  _showFilterRow
                      ? Icons.close_fullscreen
                      : Icons.filter_alt_outlined,
                ),
                iconSize: 18,
                color: const Color(0xFF94A3B8),
                tooltip: _showFilterRow ? 'Hide Filters' : 'Show Filters',
                onPressed: () {
                  setState(() {
                    _showFilterRow = !_showFilterRow;
                  });
                },
              ),

              SizedBox(width: 10),
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: Color(0xFFE2E8F0), width: 1),
                ),
                child: Row(
                  children: [
                    Container(
                      // color: Colors.yellow.shade50,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            isActionable ? "OFF" : "ON",
                            style: GoogleFonts.poppins(
                              fontSize: 10,
                              color: !isActionable ? Colors.green : Colors.grey,
                            ),
                          ),
                          SizedBox(
                            height: 10,
                            width: 30,
                            child: Padding(
                              padding: EdgeInsets.zero,
                              child: Transform.scale(
                                scale: 0.4,
                                child: Switch(
                                  value: !isActionable,
                                  onChanged: (v) async {
                                    bool newValue = !v;
                                    setState(() {
                                      isActionable = newValue;
                                      userPreference =
                                          newValue; // Save this as the new "normal"
                                    });
                                    final prefs =
                                    await SharedPreferences.getInstance();
                                    await prefs.setBool(
                                      'isActionable',
                                      newValue,
                                    );
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Tooltip(
                      message: 'Set AutoRefresh Timer',
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 5),
                        decoration: BoxDecoration(
                          // color: Colors.white,
                          // borderRadius: BorderRadius.circular(30),
                          border: Border(
                            left: BorderSide(
                              color: Color(0xFFE2E8F0),
                              width: 2,
                            ),
                          ),
                        ),
                        height: 30,
                        child: DropdownButton<int>(
                          value: selectedSeconds,
                          underline: SizedBox(),
                          items: [30, 45, 60].map((e) {
                            return DropdownMenuItem(
                              value: e,
                              child: Text(
                                "$e sec",
                                style: GoogleFonts.poppins(fontSize: 11),
                              ),
                            );
                          }).toList(),
                          onChanged: (value) async {
                            setState(() {
                              selectedSeconds = value!;
                              startTimer(); // restart timer with new value
                            });

                            final prefs = await SharedPreferences.getInstance();
                            await prefs.setInt('selectedSeconds', value!);
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 10),
              MouseRegion(
                onEnter: (_) {
                  // setState(() {
                  //   isActionable = true;
                  // });
                },
                onExit: (_) {
                  // setState(() {
                  //   // isActionable = false;
                  //   isActionable = _searchStaffController.text.isNotEmpty;
                  // });
                },
                child: ThemedSearchField(
                  hintText: 'Search',
                  backgroundColor: Color(0xFFFFFFFF),
                  txtHeight: 30,
                  controller: _searchStaffController,
                  txtwidth: ResponsiveLayout.isMobile(context)
                      ? MediaQuery
                      .of(context)
                      .size
                      .width * 0.7
                      : MediaQuery
                      .of(context)
                      .size
                      .width * 0.13,

                  // Combine the logic into one function block
                  onChanged: (value) {
                    // 1. Call your existing filter function
                    filterData(value);

                    // 2. Perform the logic to toggle the switch UI
                    setState(() {
                      if (value.isNotEmpty) {
                        // CASE 1: Searching -> Force switch to "OFF" (isActionable = true)
                        isActionable = true;
                      } else {
                        // CASE 2: Search cleared -> Restore the status from memory
                        isActionable = userPreference;
                      }
                    });
                  },
                ),
              ),
              SizedBox(width: 10),
              ExportBtn(
                sheetName: "Enquiry",
                fileName: "Enquiry_list",
                data: filteredData,
                txt: !ResponsiveLayout.isMobile(context) ? true : false,
                displayHeaders: [
                  // "Received Date & Time",
                  // "Created Date & Time",
                  "Received Date",
                  "Assigned To",
                  "Partner Code",
                  "Partner Name",
                  "Insurer",
                  "Insured Name",
                  "Vehicle.No.",
                  "Assigned Date & Time",
                  "Premium",
                  "Payment Mode",
                  "Vehicle Type",
                  "Policy Number",
                  "Status",
                ],
                keys: [
                  // "created_on",
                  "enquiry_created_on",
                  "assigned_to_name",
                  "agent_code",
                  "agent_name",
                  "insurer_short_name",
                  "insured_name",
                  "reg_no",
                  "updated_on",
                  "premium_amount",
                  "payment_mode_value",
                  "vehicle_type",
                  "policy_number",
                  "status",
                ],
              ),
            ],
          ),
        ),

        // SizedBox(height: 5),
        SizedBox(child: _buildStyledTabs()),
        ResponsiveLayout.isMobile(context)
            ? _buildDataTable(context)
            : Container(
          height: MediaQuery
              .of(context)
              .size
              .height * 0.55,
          // decoration: BoxDecoration(
          //     color: Colors.white
          // ),
          child: _buildDataTable(context),
        ),
      ],
    );
  }

  // 1. Add group expansion state tracking
  Map<String, bool> groupExpanded = {
    'To be assigned': true,
    'Assigned': true,
    'In progress': true,
  };

  Map<String, String> statusGroupMap = {
    'To be assigned': 'To Be Assigned',
    'Assigned': 'Assigned',
    'In progress': 'In Progress',
  };

  List<Map<String, dynamic>> get filteredDataByTab {
    final sortedData = [...filteredData]
      ..sort((a, b) => int.parse(b['id']) - int.parse(a['id']));

    if (sortedData.isEmpty) return [];

    if (selectedIndex == 0) {
      return sortedData.where((e) {
        return [
          "To be assigned",
          "Assigned",
          "In progress",
        ].contains(e['enquiry_status']);
      }).toList();
    }

    // Completed tab → ALWAYS paginate
    return paginatedCompletedData;
  }

  //  Add  group enquiries by status
  Map<String, List<Map<String, dynamic>>> get _groupedEnquiries {
    final Map<String, List<Map<String, dynamic>>> grouped = {};

    if (selectedIndex == 0) {
      grouped["To be assigned"] = [];
      grouped["Assigned"] = [];
      grouped["In progress"] = [];
    } else {
      grouped["Completed"] = [];
    }

    for (var item in filteredDataByTab) {
      final status = (item['enquiry_status'] ?? '').toString();
      if (grouped.containsKey(status)) {
        grouped[status]!.add(item);
      }
    }

    return grouped;
  }

  final Map<String, Color> statusColors = {
    'Awaiting Proposal': const Color(0xFFEFF6FF), // Blue 50
    'Proposal Created': const Color(0xFFF0F9FF), // Cyan 50
    'Proposal Accepted': const Color(0xFFF0FDF4), // Green 50
    'Proposal Rejected': const Color(0xFFFEF9C3), // Yellow 50
    'Policy Created': const Color(0xFFF3F0FF),

    'To be assigned': const Color(0xFFEFF6FF), // Blue 50
    'Assigned': const Color(0xFFFEF9C3), // Cyan 50
    'In progress': const Color(0xFFF0FDF4), // Green 50
    'Completed': const Color(0xFFF3F0FF), // Purple 50 (generated)
  };

  final Map<String, Color> statusBorderColors = {
    'Awaiting Proposal': const Color(0xFFDBEAFE), // Blue 100
    'Proposal Created': const Color(0xFFBAE6FD), // Cyan 100
    'Proposal Accepted': const Color(0xFFDCFCE7), // Green 100
    'Proposal Rejected': const Color(0xFFFEF3C7), // Yellow 100
    'Policy Created': const Color(0xFFF0E4FF), // Purple 200

    'To be assigned': const Color(0xFFDBEAFE), // Blue 100
    'Assigned': const Color(0xFFFEF3C7), // Cyan 100
    'In progress': const Color(0xFFDCFCE7), // Green 100
    'Completed': const Color(0xFFF0E4FF), // Purple 200
    // 'Policy Created': const Color(0xFFE5CCFF), // Purple 200
  };

  // 4. Build group header widget
  Widget _buildGroupHeader(String status, int count) {
    final isExpanded = groupExpanded[status] ?? true;

    return InkWell(
      onTap: () {
        setState(() {
          groupExpanded[status] = !isExpanded;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 2),
        child: Row(
          children: [
            Icon(
              isExpanded ? Icons.arrow_drop_down : Icons.arrow_right,
              size: 22,
              color: Color(0xFF5A6C7D),
            ),
            SizedBox(width: 8),
            Text(
              // '${config['icon']} $status',
              _formatStatus(status),
              style: GoogleFonts.inter(
                fontSize: 13,
                color: Colors.black,
                // color: Colors.orange,
                fontWeight: FontWeight.w600,
              ),
            ),
            // Spacer(),
            SizedBox(width: 8),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 2),
              decoration: BoxDecoration(
                color: Color(0xFFEFF6FF),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '$count',
                style: GoogleFonts.inter(
                  fontSize: 11,
                  color: Color(0xFF2563EB),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDataTable(context) {
    final screenWidth = MediaQuery
        .of(context)
        .size
        .width;
    final isMobile = ResponsiveLayout.isMobile(context);

    // Calculate minimum width based on screen size
    double minTableWidth = isMobile ? screenWidth * 1.2 : 1200;
    return
      // Expanded(
      // child:
      LayoutBuilder(
        builder: (context, constraints) {
          double tableWidth = constraints.maxWidth > minTableWidth
              ? constraints.maxWidth
              : minTableWidth;

          final isDesktop = !ResponsiveLayout.isMobile(context);

          return ScrollConfiguration(
            behavior: const MaterialScrollBehavior().copyWith(
              dragDevices: {PointerDeviceKind.mouse, PointerDeviceKind.touch},
            ),
            child: SingleChildScrollView(
              controller: _horizontalScrollController, // 👈 Shared controller
              scrollDirection: Axis.horizontal,
              child: SizedBox(
                // width: minWidth,
                width: tableWidth,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Fixed Header
                    Container(
                      decoration: BoxDecoration(
                        // color: Colors.white,
                        color: Color(0xFFF1F5F9),
                        borderRadius: BorderRadius.circular(5),
                      ),
                      child: _buildTableHeader(isDesktop),
                    ),

                    // Scrollable Data Content
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(color: Colors.white),
                        child: _buildDataTableContent(), // 👈 New method
                      ),
                    ),
                    _buildPaginationControls(),
                  ],
                ),
              ),
            ),
          );
        },
      );
    // );
  }

  // Replace your _buildDataTableContent() method with this optimized version

  Widget _buildDataTableContent() {
    if (filteredData.isEmpty) {
      return const SizedBox(
        height: 50,
        child: Center(child: Text('No available data')),
      );
    }

    final groupedData = _groupedEnquiries;

    // Flatten the grouped data into a single list with group headers
    final List<dynamic> flattenedList = [];

    groupedData.entries.forEach((entry) {
      final status = entry.key;
      final items = entry.value;

      if (items.isNotEmpty) {
        // Add group header
        flattenedList.add({
          'type': 'header',
          'status': status,
          // 'count': items.length,
          'count': selectedIndex == 1
              ? fullCompletedCount // <-- Show full completed count
              : items.length, // For progress, show filtered count
          'isExpanded': groupExpanded[status] ?? true,
        });

        // Add items if expanded
        if (groupExpanded[status] ?? true) {
          flattenedList.addAll(
            items.map((item) => {'type': 'item', 'data': item}),
          );
        }
      }
    });

    return ListView.builder(
      itemCount: flattenedList.length,
      itemBuilder: (context, index) {
        final item = flattenedList[index];

        if (item['type'] == 'header') {
          // Render group header
          return Container(
            width: MediaQuery
                .of(context)
                .size
                .width,
            margin: EdgeInsets.fromLTRB(12, 4, 12, 4),
            child: _buildGroupHeader(item['status'], item['count']),
          );
        } else {
          // Render data row
          final data = item['data'];
          final sno = index; // You can calculate proper serial number if needed
          final id = int.tryParse(data['id'].toString()) ?? 0;
          final selectId = data['id'].toString() ?? '0';

          return Container(
            width: MediaQuery
                .of(context)
                .size
                .width,
            margin: EdgeInsets.fromLTRB(12, 8, 12, 8),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Color(0xFFFFECF1F7)),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                DataTable(
                  border: TableBorder.all(color: Colors.transparent, width: 0),
                  headingRowHeight: 0,
                  dividerThickness: 0.1,
                  columnSpacing: 20.0,
                  dataRowMinHeight: 40,
                  columns: _buildDataColumns(),
                  rows: [_buildDataRow(data, sno)],
                ),

                // Expanded content
                if (rowExpanded[id] ?? false)
                  Container(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width,
                    decoration: BoxDecoration(
                      border: Border.all(color: Color(0xFFC7D2FE)),
                      color: Color(0xFFF8F9FF),
                    ),
                    padding: const EdgeInsets.symmetric(
                      vertical: 14.0,
                      horizontal: 8.0,
                    ),
                    child: SubRowWidget(
                      selectId: selectId,
                      rowId: id,
                      onSave: handleSave,
                      onClose: () {
                        setState(() => rowExpanded.clear());
                      },
                      controllers: controllers,
                      selectedAgent: selectedAgent,
                      selectedStaff: selectedStaff,
                      selectedBroker: selectedBroker,
                      selectedInsurer: selectedInsurer,
                      // selectedVehicleType: selectedVehicleType,
                      filteredAgentData: filteredAgentData,
                      filteredStaffDataEnqAsgn: filteredStaffDataEnqAsgn,
                      onStaffChanged: (val) {
                        setState(() {
                          selectedStaff = val;
                        });
                      },
                      onAgentChanged: (val) {
                        setState(() {
                          selectedAgent = val;
                        });
                      },
                      onInsurerChanged: (val) {
                        setState(() {
                          selectedInsurer = val;
                        });
                      },
                      // onVehicleTypeChanged: (val) {
                      //   setState(() {
                      //     selectedVehicleType = val;
                      //   });
                      // },
                      onBrokerChanged: (val) {
                        setState(() {
                          selectedBroker = val;
                        });
                      },
                    ),
                  ),
              ],
            ),
          );
        }
      },
    );
  }

  // Add this helper method to generate DataColumns
  List<DataColumn> _buildDataColumns() {
    return [
      DataColumn(label: Text('Received Date', style: _headerStyle)),
      // DataColumn(label: Text('Enquiry Created Date', style: _headerStyle)),
      DataColumn(label: Text('Assigned To', style: _headerStyle)),
      DataColumn(label: Text('Partner', style: _headerStyle)),

      // const DataColumn(label: Text('Broker *', style: _headerStyle)),
      DataColumn(label: Text('Insurer', style: _headerStyle)),
      DataColumn(label: Text('Insured Name', style: _headerStyle)),
      DataColumn(label: Text('Vehicle No', style: _headerStyle)),
      DataColumn(label: Text('Action', style: _headerStyle)),
      DataColumn(label: Text('Status', style: _headerStyle)),
      // const DataColumn(label: Text('Assigned Date', style: _headerStyle)),
      // DataColumn(label: Text('Premium', style: _headerStyle)),
      DataColumn(label: Text('Payment Mode', style: _headerStyle)),
      DataColumn(label: Text('Plan Type', style: _headerStyle)),
      DataColumn(label: Text('Vehicle Type', style: _headerStyle)),
      DataColumn(label: Text('Policy', style: _headerStyle)),
    ];
  }

  Widget _buildTableHeader(bool isDesktop) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          _buildHeaderCell('Received Date', 110),
          // _buildHeaderCell('Enquiry Created Date', 110),
          _buildHeaderCell('Assigned To', 110),
          _buildHeaderCell('Partner', 100),

          // _buildHeaderCell('Broker *', 100),
          _buildHeaderCell('Insurer', 90),
          _buildHeaderCell('Insured Name', 110),
          _buildHeaderCell('Vehicle No ', 90),
          _buildHeaderCell('Action', 110),
          _buildHeaderCell('Status', 100),
          // _buildHeaderCell('Assigned Date', 100),
          // _buildHeaderCell('Premium', 100),
          _buildHeaderCell('Payment Mode', 100),
          _buildHeaderCell('Plan Type', 100),
          _buildHeaderCell('Vehicle Type', 100),

          _buildHeaderCell('Policy', 100),
        ],
      ),
    );
  }

  Widget _buildHeaderCell(String label, double width) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4),
      child: SizedBox(
        width: width,
        child: Text(
          label,
          style: GoogleFonts.poppins(
            fontSize: 11,
            fontWeight: FontWeight.w500,
            color: Color(0xFF1E293B),
            // color: Colors.black87,
          ),
        ),
      ),
    );
  }

  // Optimized _buildDataRow - Extract reusable widgets and reduce nesting

  // 1. First, add these helper widget methods to your class:

  // Helper: Build action buttons
  Widget _buildActionButtons(
      Map<String, dynamic> item,
      int id,
      String selectId,
      ) {
    return Row(
      children: [
        _buildInfoTooltip(item),
        _buildEditButton(item, id),
        _buildFileUploadButton(selectId),
        if (item['enquiry_status'] != 'Completed' && roleId == 'manager')
          _buildDeleteButton(item),
      ],
    );
  }

  // Helper: Info tooltip
  Widget _buildInfoTooltip(Map<String, dynamic> item) {
    return Tooltip(
      richMessage: WidgetSpan(
        child: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Color(0xFFFFFCF2),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _row("Email", item["email"] != null ? item["email"] : ''),
              _row("Mobile", item["mobile"] != null ? item["mobile"] : ''),
              _row("Remarks", item["remarks"] != null ? item["remarks"] : ''),
            ],
          ),
        ),
      ),
      padding: EdgeInsets.zero,
      verticalOffset: 12,
      waitDuration: Duration(milliseconds: 500),
      showDuration: Duration(seconds: 2),
      decoration: BoxDecoration(),
      child: Icon(Icons.info_outline_rounded, size: 15, color: Colors.blue),
    );
  }

  // Helper: Edit button
  Widget _buildEditButton(Map<String, dynamic> item, int id) {
    return IconButton(
      padding: EdgeInsets.zero,
      constraints: BoxConstraints(minWidth: 24, minHeight: 24),
      icon: Icon(
        rowExpanded[id] == true ? Icons.edit_off_sharp : Icons.edit,
        color: Colors.blue,
        size: 15,
      ),
      tooltip: "Edit",
      onPressed: () {
        setState(() {
          bool isOpen = rowExpanded[id] ?? false;
          rowExpanded.clear();
          if (!isOpen) rowExpanded[id] = true;
        });
        handleEdit(item);
      },
    );
  }

  // Helper: File upload button with menu
  Widget _buildFileUploadButton(String selectId) {
    return Builder(
      builder: (buttonContext) => Material(
        color: Colors.white,
        child: InkWell(
          onTap: () async {
            final button = buttonContext.findRenderObject() as RenderBox;
            final overlay =
            Overlay.of(buttonContext).context.findRenderObject()
            as RenderBox;
            final position = button.localToGlobal(
              Offset.zero,
              ancestor: overlay,
            );

            await showMenu(
              context: buttonContext,
              position: RelativeRect.fromLTRB(
                position.dx,
                position.dy + button.size.height,
                overlay.size.width,
                0,
              ),
              items: [
                PopupMenuItem(child: MultipleFileWidget(enqId: selectId)),
              ],
              color: Colors.white,
            );
          },
          child: Tooltip(
            message: 'Click and Upload / Download Enquiry Files',
            waitDuration: Duration(milliseconds: 500),
            showDuration: Duration(seconds: 2),
            child: Icon(
              Icons.file_upload_outlined,
              size: 15,
              color: Colors.green,
            ),
          ),
        ),
      ),
    );
  }

  // Helper: Delete button
  Widget _buildDeleteButton(Map<String, dynamic> item) {
    return IconButton(
      padding: EdgeInsets.zero,
      constraints: BoxConstraints(minWidth: 24, minHeight: 24),
      icon: Icon(Icons.delete, color: Colors.red.shade400, size: 15),
      tooltip: "Delete Enquiry",
      onPressed: () => handleDeleteEnq(item),
    );
  }

  // Helper: Status cell with conditional actions
  Widget _buildStatusCell(
      Map<String, dynamic> item,
      int id,
      Color bgColor,
      Color borderColor,
      ) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (item['enquiry_status'] != 'Assigned')
          _buildStatusContainer(item, id, bgColor, borderColor),
        if (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] != null)
          _buildProceedButton(id),
        if (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] == null)
          _buildCreateQuoteButton(item),
      ],
    );
  }

  String formatEnquiryStatus(String? status) {
    if (status == null || status.trim().isEmpty) return '-';

    switch (status.trim().toLowerCase()) {
      case 'to be assigned':
        return 'To Be Assigned';
      case 'in progress':
        return 'In Progress';
      case 'assigned':
        return 'Assigned';
      case 'completed':
        return 'Completed';
      default:
        return status; // fallback
    }
  }

  // Helper: Status display container
  Widget _buildStatusContainer(
      Map<String, dynamic> item,
      int id,
      Color bgColor,
      Color borderColor,
      ) {
    return Material(
      color: Colors.white,
      child: InkWell(
        hoverColor: Color(0xFFEAF6F4),
        onTap: null,

        child: Container(
          padding: EdgeInsets.symmetric(vertical: 2.0),
          margin: EdgeInsets.symmetric(vertical: 2),
          decoration: BoxDecoration(
            color: bgColor,
            border: Border.all(color: borderColor),
            borderRadius: BorderRadius.circular(5),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                // item['enquiry_status'] ?? '-',
                formatEnquiryStatus(item['enquiry_status']),
                style: GoogleFonts.inter(
                  fontSize: 10,
                  color: Color(0XFF1e293b),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // Helper: Proceed button
  Widget _buildProceedButton(int id) {
    return TextButton(
      onPressed: () async {
        final res = await apiService.updateEnquiryInProgress(id);
        if (res['status'] == 'success') refrshfilterDateRange();
      },
      child: Tooltip(
        message: 'Click to Proceed',
        waitDuration: Duration(milliseconds: 500),
        showDuration: Duration(seconds: 2),
        child: Text(
          'PROCEED',
          style: GoogleFonts.poppins(
            fontSize: 11,
            fontWeight: FontWeight.w500,
            color: Colors.green,
          ),
        ),
      ),
    );
  }

  // Helper: Create quote button
  Widget _buildCreateQuoteButton(Map<String, dynamic> item) {
    return TextButton(
      onPressed: () async {
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove('enqStaffDataId');
        await prefs.setString('enqStaffDataId', item['id'].toString());
        ref.read(quotationStaffIdProvider.notifier).state = item['id'];
        buildStatusActions(context, item['status'], item['id']);
      },
      child: Tooltip(
        message: 'Click to Create Quote',
        waitDuration: Duration(milliseconds: 500),
        showDuration: Duration(seconds: 2),
        child: Text(
          'Create Quote',
          style: GoogleFonts.poppins(
            fontSize: 11,
            fontWeight: FontWeight.w500,
            color: Colors.blue,
          ),
        ),
      ),
    );
  }

  // Helper: Payment mode dropdown
  Widget _buildPaymentModeDropdown(Map<String, dynamic> item) {
    if (item['enquiry_status'] == 'To be assigned' ||
        (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] == null)) {
      return Text('-');
    }

    return DropdownSearch<Map<String, dynamic>>(
      key: ValueKey('payment_${item['id']}'),
      selectedItem: _getSelectedPaymentMode(item),
      items: (filter, _) async => _filterPaymentModes(filter),
      itemAsString: (val) => val['value'].toString(),
      compareFn: (item, selectedItem) => item['id'] == selectedItem['id'],
      suffixProps: _buildDropdownSuffix(),
      dropdownBuilder: (context, selectedItem) =>
          _buildDropdownDisplay(selectedItem, 'value', 'Select Payment Mode'),
      decoratorProps: _buildDropdownDecorator(),
      popupProps: _buildDropdownPopup('value'),
      onChanged: (val) {
        if (val != null) {
          setState(() {
            item['payment_mode_id'] = val['id'].toString();
            item['payment_mode'] = val['value'].toString();
          });
          handlePaymentMode(val['id'].toString(), item['quotation_id']);
        }
      },
    );
  }

  // Helper: Insurance plan type dropdown
  Widget _buildInsurancePlanDropdown(Map<String, dynamic> item) {
    if (item['enquiry_status'] == 'To be assigned' ||
        (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] == null)) {
      return Text('-');
    }

    return DropdownSearch<Map<String, dynamic>>(
      key: ValueKey('insurance_${item['id']}'),
      selectedItem: _getSelectedInsurancePlan(item),
      items: (filter, _) async => _filterInsurancePlans(filter),
      itemAsString: (val) => val['insurance_plan_type'].toString(),
      compareFn: (item, selectedItem) => item['id'] == selectedItem['id'],
      suffixProps: _buildDropdownSuffix(),
      dropdownBuilder: (context, selectedItem) => _buildDropdownDisplay(
        selectedItem,
        'insurance_plan_type',
        'Select Insurer',
      ),
      decoratorProps: _buildDropdownDecorator(),
      popupProps: _buildDropdownPopup('insurance_plan_type'),
      onChanged: (val) {
        if (val != null) {
          setState(() {
            item['insurance_plan_type'] = val['insurance_plan_type'].toString();
          });
          handleInsurancePlanTypeMode(
            val['id'].toString(),
            item['quotation_id'],
          );
        }
      },
    );
  }

  // Helper: Vehicle type dropdown
  Widget _buildVehicleTypeDropdown(Map<String, dynamic> item) {
    if (item['enquiry_status'] == 'To be assigned' ||
        (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] == null)) {
      return Text('-');
    }

    return DropdownSearch<Map<String, dynamic>>(
      key: ValueKey('vehicle_type_${item['id']}'),
      selectedItem: _getSelectedVehicleType(item),
      items: (filter, _) async => _filterVehicleType(filter),
      itemAsString: (val) => val['vehicle_type'].toString(),
      compareFn: (item, selectedItem) => item['vehicle_type_id'] == selectedItem['id'],
      suffixProps: _buildDropdownSuffix(),
      dropdownBuilder: (context, selectedItem) =>
          _buildDropdownDisplay(selectedItem, 'vehicle_type', 'Select Vehicle Type'),
      decoratorProps: _buildDropdownDecorator(),
      popupProps: _buildDropdownPopup('vehicle_type'),
      onChanged: (val) {
        if (val != null) {
          setState(() {
            item['vehicle_type_id'] = val['id'].toString();
            item['vehicle_type'] = val['vehicle_type'].toString();
          });
          handleVehicleType(val['id'].toString(), item['id']);
        }
      },
    );
  }

  // Helper: Policy upload/download
  Widget _buildPolicyCell(Map<String, dynamic> item) {
    if (item['enquiry_status'] == 'To be assigned' ||
        (item['enquiry_status'] == 'Assigned' &&
            item['quotation_id'] == null)) {
      return Text('-');
    }

    return Row(
      children: [
        if (item['enquiry_status'] == 'Completed' &&
            item['quotation_id'] != null)
          _buildPolicyDownloadButton(item),
        _buildPolicyUploadButton(item),
      ],
    );
  }

  // Helper: Policy download button
  Widget _buildPolicyDownloadButton(Map<String, dynamic> item) {
    return Tooltip(
      message: 'Download Policy File',
      child: InkWell(
        onTap: () => apiService.downloadFile(
          apiUrl:
          'policy/downloadPolicyFile?policy_id=${item["policy_id"]}&file_type=policy_pdf',
          apiId: item["policy_id"],
          localFile: null,
          fileName: item['policy_pdf_file_name'],
        ),
        child: Icon(Icons.file_download, size: 14, color: Colors.blueAccent),
      ),
    );
  }

  // Helper: Policy upload button with menu
  Widget _buildPolicyUploadButton(Map<String, dynamic> item) {
    return Builder(
      builder: (buttonContext) => Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {
            if (item['payment_mode_id'] != null) {
              _showPolicyUploadMenu(buttonContext, item);
            } else {
              ToastHelper.showErrorToast(context, 'Please select payment mode');
            }
            if (item['vehicle_type'] != null) {
              _showPolicyUploadMenu(buttonContext, item);
            } else {
              ToastHelper.showErrorToast(context, 'Please select vehicle type');
            }
          },
          child: Tooltip(
            message: 'Click and Upload Policy PDF',
            waitDuration: Duration(milliseconds: 500),
            showDuration: Duration(seconds: 2),
            child: Icon(
              Icons.file_upload_outlined,
              size: 15,
              color: Colors.green,
            ),
          ),
        ),
      ),
    );
  }

  // Helper: Show policy upload menu
  Future<void> _showPolicyUploadMenu(
      BuildContext buttonContext,
      Map<String, dynamic> item,
      ) async {
    final button = buttonContext.findRenderObject() as RenderBox;
    final overlay =
    Overlay.of(buttonContext).context.findRenderObject() as RenderBox;
    final position = button.localToGlobal(Offset.zero, ancestor: overlay);

    await showMenu(
      context: buttonContext,
      position: RelativeRect.fromLTRB(
        position.dx,
        position.dy + button.size.height,
        overlay.size.width,
        0,
      ),
      items: [
        PopupMenuItem(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('Upload Policy PDF', style: _dataBold),
              SizedBox(height: 10),
              _buildPolicyUploadField(item),
            ],
          ),
        ),
      ],
      color: Colors.white,
    );
  }

  // Helper: Policy upload field

  Widget _buildPolicyUploadField(Map<String, dynamic> item) {
    return ThemedUploadField(
      hintText:
      selectedFileNames ??
          item['policy_pdf_file_name'] ??
          "Upload Document",
      padHorizontal: 4,
      padVertical: 5,
      fontSZ: 11,
      borderCirculr: 5,
      txtwidth: ResponsiveLayout.isMobile(context)
          ? null
          : MediaQuery.of(context).size.width * 0.18,
      borderColor: Color(0xFFE2E8F0),
      onFileSelected: (fileName, file) =>
          _handlePolicyFileUpload(fileName, file, item),
    );
  }

  // Helper: Handle policy file upload
  Future<void> _handlePolicyFileUpload(
      String? fileName,
      PlatformFile? file,
      Map<String, dynamic> item,
      ) async {
    if (lastPickedFile == fileName) {
      ToastHelper.showErrorToast(context, 'Please upload a new file.');
      setState(() {
        selectedFileNames = null;
        docUploadedFile = null;
      });
      return;
    }

    if (file == null ||
        fileName == null ||
        fileName.isEmpty ||
        file.size == 0) {
      return;
    }

    if (!fileName.toLowerCase().endsWith('.pdf')) {
      ToastHelper.showErrorToast(context, 'Only PDF files are allowed.');
      return;
    }

    lastPickedFile = fileName;
    setState(() => docUploadedFile = file);

    await uploadPolicyPDF(
      file: docUploadedFile,
      data: {
        "quotation_id": item["quotation_id"],
        "manager_id": managerId,
        "created_by": userId,
        "updated_by": userId,
        "id": item["policy_id"],
      },
    );
    Navigator.of(context).pop();
  }

  // Helper methods for dropdown reusability
  Map<String, dynamic>? _getSelectedPaymentMode(Map<String, dynamic> item) {
    try {
      return filteredPaymentModeData.firstWhere(
            (mode) => mode['id'].toString() == item['payment_mode_id'].toString(),
        orElse: () => {},
      );
    } catch (e) {
      return null;
    }
  }

  Map<String, dynamic>? _getSelectedInsurancePlan(Map<String, dynamic> item) {
    try {
      return filteredInsuranceData.firstWhere(
            (mode) =>
        mode['insurance_plan_type'].toString().trim().toLowerCase() ==
            item['insurance_plan_type'].toString().trim().toLowerCase(),
        orElse: () => {},
      );
    } catch (e) {
      return null;
    }
  }

  Map<String, dynamic>? _getSelectedVehicleType(Map<String, dynamic> item) {
    try {

      print('EIL 1getSVT-called');
      // print('EIL 2getSVT-vehicle_type_id  ${item['vehicle_type_id']}');
      // print('EIL 3getSVT-vehicle_type  ${item['vehicle_type']}');

      final result = filteredVehicleData.firstWhere(
            (vt) {
          final idMatch =
              vt['id'].toString() == item['vehicle_type_id'].toString();

          final nameMatch =
              vt['vehicle_type'].toString().trim().toLowerCase() ==
                  item['vehicle_type'].toString().trim().toLowerCase();

          // print('EIL 3getSVT-check  id O:${vt['id']} | name O:${vt['vehicle_type']} '); // o means original
          // print('EIL 4getSVT-check  id M:$idMatch | name M:$nameMatch'); // M means match

          return idMatch || nameMatch;
        },
        orElse: () => {},
      );

      print('EIL 5getSVT-result $result');

      return result.isNotEmpty ? result : null;
    } catch (e, s) {
      print('EIL 6getSVT-ERROR $e');
      print(s);
      return null;
    }
  }


  List<Map<String, dynamic>> _filterPaymentModes(String filter) {
    if (filter.isEmpty) return filteredPaymentModeData;
    return filteredPaymentModeData.where((mode) {
      return mode['value'].toString().toLowerCase().contains(
        filter.toLowerCase(),
      );
    }).toList();
  }

  List<Map<String, dynamic>> _filterInsurancePlans(String filter) {
    if (filter.isEmpty) return filteredInsuranceData;
    return filteredInsuranceData.where((plan) {
      return plan['insurance_plan_type'].toString().toLowerCase().contains(
        filter.toLowerCase(),
      );
    }).toList();
  }

  List<Map<String, dynamic>> _filterVehicleType(String filter) {
    print('EIL 1filterVT-called');
    print('EIL 2filterVT-text "$filter" | ${filteredVehicleData.length}');

    if (filter.isEmpty) return filteredVehicleData;  // 'Filter EMPTY → returning full list'

    final result = filteredVehicleData.where((vt) {
      final vehicleType = vt['vehicle_type']?.toString().toLowerCase() ?? '';
      final match = vehicleType.contains(filter.toLowerCase());
      print('EIL 3filterVT-Check - id:${vt['id']} | vehicle_type:$vehicleType | match:$match');
      return match;
    }).toList();

    return result;
  }


  DropdownSuffixProps _buildDropdownSuffix() {
    return DropdownSuffixProps(
      dropdownButtonProps: DropdownButtonProps(
        isVisible: true,
        padding: EdgeInsets.zero,
        constraints: BoxConstraints(minWidth: 12, minHeight: 12),
        iconSize: 8,
        color: Colors.black45,
      ),
    );
  }

  Widget _buildDropdownDisplay(dynamic selectedItem, String key, String hint) {
    bool isEmpty =
        selectedItem == null ||
            selectedItem.isEmpty ||
            selectedItem[key] == null;

    return Container(
      padding: EdgeInsets.zero,
      alignment: Alignment.centerLeft,
      child: Text(
        isEmpty ? hint : selectedItem[key].toString(),
        style: GoogleFonts.poppins(
          fontSize: 11,
          color: isEmpty ? Colors.grey.shade500 : Colors.black,
          fontWeight: FontWeight.w400,
        ),
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
        softWrap: false,
      ),
    );
  }

  DropDownDecoratorProps _buildDropdownDecorator() {
    return DropDownDecoratorProps(
      decoration: AppInputDecorations.dropdownDecoration().copyWith(
        filled: true,
        fillColor: Colors.white,
        isDense: true,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(color: Color(0xFFE2E8F0), width: 0.5),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(color: Color(0xFFE2E8F0), width: 0.5),
        ),
        contentPadding: EdgeInsets.symmetric(horizontal: 1, vertical: 6),
      ),
    );
  }

  // 2. Now the OPTIMIZED _buildDataRow method:
  DataRow _buildDataRow(Map<String, dynamic> item, int sno) {
    final id = int.tryParse(item['id'].toString()) ?? 0;
    final selectId = item['id'].toString() ?? '0';
    final status = item['enquiry_status'] ?? '-';
    final bgColor = statusColors[status] ?? Color(0xFFF9FAFB);
    final borderColor = statusBorderColors[status] ?? Color(0xFFE2E8F0);

    return DataRow(
      cells: [
        // Enquiry Created Date
        DataCell(
          SizedBox(
            width: 70,
            child: Text(
              item['enquiry_created_on'],
              style: _dataBoldthm1,
            ),
          ),
        ),

        // Assigned To
        DataCell(
          SizedBox(
            width: 110,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  item['assigned_to_name'] != null
                      ? _truncateText(item['assigned_to_name'], 15)
                      : '-',
                  style: _dataBold,
                ),
                Text(
                  item['updated_on'] != null
                      ? _formatDate(item['updated_on'])
                      : '-',
                  style: _dataBoldthm4,
                ),
              ],
            ),
          ),
        ),

        // Partner
        DataCell(
          SizedBox(
            width: 100,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(item['agent_code'] ?? '-', style: _dataBold),
                Text(
                  item['agent_name'] != null
                      ? _truncateText(item['agent_name'], 20)
                      : '-',
                  style: _tableDataTimeStyle,
                ),
              ],
            ),
          ),
        ),

        // Insurer
        DataCell(
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                width: 60,
                child: Text(
                  item['insurer_short_name'] ?? '-',
                  style: _dataBoldthm2,
                ),
              ),
              Tooltip(
                message: 'Broker : ${item['broker_name']}',
                child: Text(
                  item['broker_name'] != null
                      ? _truncateText(item['broker_name'], 8)
                      : '-',
                  style: _dataBoldthm4,
                ),
              ),
            ],
          ),
        ),

        // Insured Name
        DataCell(
          SizedBox(
            width: 90,
            child: Tooltip(
              message: item['insured_name'] ?? '-',
              child: Text(
                item['insured_name'] != null
                    ? _truncateText(item['insured_name'], 15)
                    : '-',
                style: _dataBoldthm2,
              ),
            ),
          ),
        ),

        // Vehicle No
        DataCell(
          SizedBox(
            width: 95,
            child: Container(
              padding: EdgeInsets.all(4.0),
              margin: EdgeInsets.symmetric(vertical: 3, horizontal: 2),
              decoration: BoxDecoration(
                color: Color(0xFFF9FAFB),
                border: Border.all(color: Color(0xFFE2E8F0)),
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(item['reg_no'] ?? '-', style: _dataBoldthm3),
            ),
          ),
        ),

        // Action Buttons
        DataCell(
          SizedBox(width: 80.0, child: _buildActionButtons(item, id, selectId)),
        ),

        // Status
        DataCell(
          SizedBox(
            width: 100,
            child: _buildStatusCell(item, id, bgColor, borderColor),
          ),
        ),

        // Payment Mode
        DataCell(
          SizedBox(
            height: 30,
            width: 100,
            child: _buildPaymentModeDropdown(item),
          ),
        ),

        // Plan Type
        DataCell(
          SizedBox(
            width: 100,
            height: 30,
            child: _buildInsurancePlanDropdown(item),
          ),
        ),

        // Vehicle  Type
        DataCell(
          SizedBox(
             width: 100,
             height: 30,
             child: _buildVehicleTypeDropdown(item),
          ),
        ),

        // Policy
        DataCell(
          SizedBox(height: 30, width: 90, child: _buildPolicyCell(item)),
        ),
      ],
    );
  }

  Widget _row(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            width: 70,
            child: Text(
              "$label ",
              style: GoogleFonts.poppins(
                color: Colors.black,
                fontSize: 10,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),

          SizedBox(
            width: 180,
            child: Text(
              value ?? '-',
              softWrap: true,
              maxLines: 5,

              style: GoogleFonts.poppins(
                color: Colors.black,
                fontSize: 10,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStyledTabs() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 4),
      decoration: const BoxDecoration(
        // color: Colors.white,
        // color: Colors.amber,
        // border: Border(bottom: BorderSide(color: Color(0xFFE5E5E5), width: 1)),
      ),
      child: Row(
        children: List.generate(enquiryTabs.length, (index) {
          final bool isSelected = selectedIndex == index;

          return MouseRegion(
            cursor: SystemMouseCursors.click,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  print('TAPPED TAB');
                  selectedIndex = index;

                  filteredData = (index == 0) ? inProgressData : completedData;
                  if (index == 1) {
                    completedCurrentPage = 1;
                    // final newValue = false;
                    // isActionable = newValue;
                  }

                  _searchStaffController.clear();
                });
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 250),
                curve: Curves.easeOut,
                padding: const EdgeInsets.symmetric(
                  vertical: 5,
                  horizontal: 10,
                ),

                // margin: const EdgeInsets.only(right: 24),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(6),
                  color: isSelected
                  // ? Color(0xFFF1F5F9)
                      ? const Color(0xFF2E7D6E).withOpacity(0.08)
                      : Colors.transparent,
                  border: Border.all(
                    color: isSelected
                        ? Colors.transparent
                        : Colors.blueGrey.shade50,
                    width: 1,
                  ),
                ),
                child: Column(
                  // mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      enquiryTabs[index],
                      style: GoogleFonts.poppins(
                        fontSize: 12,
                        fontWeight: isSelected
                            ? FontWeight.w600
                            : FontWeight.w400,
                        color: isSelected
                            ? const Color(0xFF2E7D6E)
                            : Colors.black87,
                      ),
                    ),

                    const SizedBox(height: 1),

                    // ▬▬ Underline Indicator ▬▬
                    AnimatedContainer(
                      duration: const Duration(milliseconds: 250),
                      height: 2,
                      width: isSelected ? 90 : 0,
                      decoration: BoxDecoration(
                        color: const Color(0xFF2E7D6E),
                        borderRadius: BorderRadius.circular(50),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  static final _dataBold = GoogleFonts.inter(
    fontSize: 11,

    fontWeight: FontWeight.w500,
    color: Colors.black,
    //  color: Color(0xFF000000),
  );
  static final _dataBoldthm1 = GoogleFonts.inter(
    fontSize: 11,

    fontWeight: FontWeight.w500,
    color: Colors.black,
    //  color: Color(0xFF000000),
  );

  static final _dataBoldthm2 = GoogleFonts.inter(
    fontSize: 11,
    fontWeight: FontWeight.w500,
    // color: Colors.black,
    color: Color(0XFF334155),
  );
  static final _dataBoldthm3 = GoogleFonts.inter(
    fontSize: 10,
    fontWeight: FontWeight.w500,
    // color: Colors.black,
    color: Color(0XFF334155),
  );
  static final _dataBoldthm4 = GoogleFonts.inter(
    fontSize: 9,
    fontWeight: FontWeight.w500,
    // color: Colors.black,
    color: Color(0XFF334155),
  );
  final _tableDataTimeStyle = GoogleFonts.inter(
    fontSize: 10,
    fontWeight: FontWeight.w400,
    color: Colors.black,
    // color: Color(0XFF94A3B8),
  );
  final _subLabelTimeStyle = GoogleFonts.inter(
    fontSize: 10,
    fontWeight: FontWeight.w400,
    color: Color(0XFF6366F1),
  );
  static final _dataBoldsmall = GoogleFonts.inter(
    fontSize: 12,

    fontWeight: FontWeight.w400,
    color: Color(0xFF000000),
  );
  static final _dataSub = GoogleFonts.inter(
    fontSize: 10,
    fontWeight: FontWeight.w300,
    color: Color(0xFF585757),
  );
  static final _headerStyle = GoogleFonts.inter(
    // color: Colors.black,
    color: Color(0xFF1E293B),
    fontWeight: FontWeight.w500,
  );
  static final _cardheaderStyle = GoogleFonts.inter(
    color: Colors.black,
    fontWeight: FontWeight.w600,
    fontSize: 12,
  );
  static final TextStyle _textStyle = GoogleFonts.inter(
    fontSize: 12,
    fontWeight: FontWeight.w600,
  );
  static const _cardBodyStyle = TextStyle(
    color: Color(0xFF545454),
    fontWeight: FontWeight.w400,
    fontSize: 12,
  );
  String _formatStatus(String status) {
    return status
        .split(' ')
        .map(
          (word) => word.isNotEmpty
          ? word[0].toUpperCase() + word.substring(1).toLowerCase()
          : '',
    )
        .join(' ');
  }

  String _truncateText(String text, int limit) {
    if (text.length <= limit) return text;
    return '${text.substring(0, limit)}...';
  }

  String _wrapText(String text, int chunkSize) {
    if (text.isEmpty) return '-';
    final buffer = StringBuffer();
    for (int i = 0; i < text.length; i += chunkSize) {
      int end = (i + chunkSize < text.length) ? i + chunkSize : text.length;
      buffer.writeln(text.substring(i, end)); // adds '\n' after each chunk
    }
    return buffer.toString().trim();
  }

  String formatDateTimeForTable(String? input, {bool newLine = false}) {
    if (input == null || input.trim().isEmpty) return '-';

    final s = input.trim();
    DateTime dt;

    try {
      // Case 1: ISO-like (yyyy-MM-dd ...), DateTime.parse will handle
      if (RegExp(r'^\d{4}-\d{2}-\d{2}').hasMatch(s)) {
        dt = DateTime.parse(s);
      }
      // Case 2: day-month-year at start (e.g. 13-11-2025 07:28 AM or 13-11-2025 07:28)
      else if (RegExp(r'^\d{2}-\d{2}-\d{4}').hasMatch(s)) {
        // Try with am/pm (hh:mm a)
        if (RegExp(r'\b(am|pm)\b', caseSensitive: false).hasMatch(s)) {
          dt = DateFormat('dd-MM-yyyy hh:mm a').parse(s);
        }
        // Try 24-hour time "dd-MM-yyyy HH:mm" or just date "dd-MM-yyyy"
        else if (RegExp(r'^\d{2}-\d{2}-\d{4}\s+\d{1,2}:\d{2}').hasMatch(s)) {
          dt = DateFormat('dd-MM-yyyy HH:mm').parse(s);
        } else {
          dt = DateFormat('dd-MM-yyyy').parse(s);
        }
      }
      // Case 3: fallback — try parse with DateTime.parse (may throw)
      else {
        dt = DateTime.parse(s);
      }

      final dateStr = DateFormat('dd-MM-yyyy').format(dt);
      final timeStr = DateFormat('hh:mm a').format(dt); // e.g. 07:28 AM

      return newLine ? '$dateStr\n$timeStr' : '$dateStr | $timeStr';
    } catch (e) {
      // If parsing fails, return original string as fallback (or '-' if empty)
      return s.isNotEmpty ? s : '-';
    }
  }

  PopupProps<Map<String, dynamic>> _buildDropdownPopup(String displayKey) {
    return PopupProps.menu(
      fit: FlexFit.loose,
      constraints: BoxConstraints(maxHeight: 300, minWidth: 200),
      menuProps: MenuProps(
        backgroundColor: Colors.white,
        elevation: 8,
        borderRadius: BorderRadius.circular(8),
      ),
      showSearchBox: true,
      searchFieldProps: TextFieldProps(
        autofocus: true,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(8),
          filled: true,
          fillColor: Color(0xFFF8FAFC),
          hintText: "Search...",
          hintStyle: GoogleFonts.inter(fontSize: 11, color: Colors.grey),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(5),
            borderSide: BorderSide(color: Color(0xFFE2E8F0)),
          ),
        ),
      ),
      itemBuilder: (context, item, isDisabled, isSelected) {
        return Container(
          color: isSelected ? Colors.blue.withOpacity(0.1) : Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
          child: Text(
            item[displayKey].toString(),
            style: GoogleFonts.inter(
              fontSize: 11,
              color: Colors.black87,
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
            ),
          ),
        );
      },
    );
  }

  // Add pagination controls widget
  Widget _buildPaginationControls() {
    if (selectedIndex != 1 || completedData.length <= 25) {
      return SizedBox.shrink();
    }
    // if (selectedIndex != 1 || completedData.length <= 25) {
    //     return SizedBox.shrink();
    //   }

    // Calculate display values based on filteredData
    final totalItems = filteredData.length;
    final startItem = ((completedCurrentPage - 1) * completedItemsPerPage) + 1;
    final endItem = (completedCurrentPage * completedItemsPerPage).clamp(
      0,
      totalItems,
    );

    return Container(
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Color(0xFFE2E8F0))),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Text(
                'Showing $startItem-$endItem of $totalItems', // ← Changed this
                style: GoogleFonts.inter(
                  fontSize: 10,
                  color: Color(0xFF64748B),
                ),
              ),
              SizedBox(width: 16),
              // Items per page dropdown
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8),
                decoration: BoxDecoration(
                  border: Border.all(color: Color(0xFFE2E8F0)),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: DropdownButton<int>(
                  value: completedItemsPerPage,
                  underline: SizedBox(),
                  isDense: true,
                  items: itemsPerPageOptions.map((int value) {
                    return DropdownMenuItem<int>(
                      value: value,
                      child: Text(
                        '$value / page',
                        style: GoogleFonts.inter(
                          fontSize: 10,
                          color: Color(0xFF334155),
                        ),
                      ),
                    );
                  }).toList(),
                  onChanged: (int? newValue) {
                    if (newValue != null) {
                      setState(() {
                        completedItemsPerPage = newValue;
                        completedCurrentPage = 1;
                      });
                    }
                  },
                ),
              ),
            ],
          ),
          // Pagination buttons remain the same
          Row(
            children: [
              IconButton(
                icon: Icon(Icons.first_page, size: 18),
                onPressed: completedCurrentPage > 1
                    ? () => setState(() => completedCurrentPage = 1)
                    : null,
                color: completedCurrentPage > 1
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'First page',
              ),
              IconButton(
                icon: Icon(Icons.chevron_left, size: 18),
                onPressed: completedCurrentPage > 1
                    ? () => setState(() => completedCurrentPage--)
                    : null,
                color: completedCurrentPage > 1
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Previous page',
              ),
              ..._buildPageNumbers(),
              IconButton(
                icon: Icon(Icons.chevron_right, size: 18),
                onPressed: completedCurrentPage < totalCompletedPages
                    ? () => setState(() => completedCurrentPage++)
                    : null,
                color: completedCurrentPage < totalCompletedPages
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Next page',
              ),
              IconButton(
                icon: Icon(Icons.last_page, size: 18),
                onPressed: completedCurrentPage < totalCompletedPages
                    ? () => setState(
                      () => completedCurrentPage = totalCompletedPages,
                )
                    : null,
                color: completedCurrentPage < totalCompletedPages
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Last page',
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPaginationControls1() {
    if (selectedIndex != 1 || completedData.length <= 25) {
      return SizedBox.shrink();
    }

    return Container(
      padding: EdgeInsets.symmetric(vertical: 2, horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Color(0xFFE2E8F0))),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Left side: Page info and items per page selector
          Row(
            children: [
              Text(
                'Showing ${((completedCurrentPage - 1) * completedItemsPerPage) + 1}-${(completedCurrentPage * completedItemsPerPage).clamp(0, filteredData.length)} of ${filteredData.length}',
                style: GoogleFonts.inter(
                  fontSize: 10,
                  color: Color(0xFF64748B),
                ),
              ),
              SizedBox(width: 16),
              // Items per page dropdown
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8),
                decoration: BoxDecoration(
                  border: Border.all(color: Color(0xFFE2E8F0)),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: DropdownButton<int>(
                  value: completedItemsPerPage,
                  underline: SizedBox(),
                  isDense: true,
                  items: itemsPerPageOptions.map((int value) {
                    return DropdownMenuItem<int>(
                      value: value,
                      child: Text(
                        '$value / page',
                        style: GoogleFonts.inter(
                          fontSize: 10,
                          color: Color(0xFF334155),
                        ),
                      ),
                    );
                  }).toList(),
                  onChanged: (int? newValue) {
                    if (newValue != null) {
                      setState(() {
                        completedItemsPerPage = newValue;
                        completedCurrentPage = 1; // Reset to first page
                      });
                    }
                  },
                ),
              ),
            ],
          ),

          // Right side: Pagination buttons
          Row(
            children: [
              // First page
              IconButton(
                icon: Icon(Icons.first_page, size: 18),
                onPressed: completedCurrentPage > 1
                    ? () => setState(() => completedCurrentPage = 1)
                    : null,
                color: completedCurrentPage > 1
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'First page',
              ),

              // Previous page
              IconButton(
                icon: Icon(Icons.chevron_left, size: 18),
                onPressed: completedCurrentPage > 1
                    ? () => setState(() => completedCurrentPage--)
                    : null,
                color: completedCurrentPage > 1
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Previous page',
              ),

              // Page numbers
              ..._buildPageNumbers(),

              // Next page
              IconButton(
                icon: Icon(Icons.chevron_right, size: 18),
                onPressed: completedCurrentPage < totalCompletedPages
                    ? () => setState(() => completedCurrentPage++)
                    : null,
                color: completedCurrentPage < totalCompletedPages
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Next page',
              ),

              // Last page
              IconButton(
                icon: Icon(Icons.last_page, size: 18),
                onPressed: completedCurrentPage < totalCompletedPages
                    ? () => setState(
                      () => completedCurrentPage = totalCompletedPages,
                )
                    : null,
                color: completedCurrentPage < totalCompletedPages
                    ? Color(0xFF2E7D6E)
                    : Colors.grey,
                tooltip: 'Last page',
              ),
            ],
          ),
        ],
      ),
    );
  }

  // Helper method to build page number buttons
  List<Widget> _buildPageNumbers() {
    List<Widget> pageButtons = [];

    // Show max 5 page numbers
    int startPage = (completedCurrentPage - 2).clamp(1, totalCompletedPages);
    int endPage = (startPage + 4).clamp(1, totalCompletedPages);

    // Adjust start if we're near the end
    if (endPage - startPage < 4) {
      startPage = (endPage - 4).clamp(1, totalCompletedPages);
    }

    for (int i = startPage; i <= endPage; i++) {
      pageButtons.add(
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 2),
          child: InkWell(
            onTap: () => setState(() => completedCurrentPage = i),
            child: Container(
              width: 32,
              height: 32,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: completedCurrentPage == i
                    ? Color(0xFF2E7D6E)
                    : Colors.transparent,
                borderRadius: BorderRadius.circular(4),
                border: Border.all(
                  color: completedCurrentPage == i
                      ? Color(0xFF2E7D6E)
                      : Color(0xFFE2E8F0),
                ),
              ),
              child: Text(
                '$i',
                style: GoogleFonts.inter(
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                  color: completedCurrentPage == i
                      ? Colors.white
                      : Color(0xFF64748B),
                ),
              ),
            ),
          ),
        ),
      );
    }

    return pageButtons;
  }
}