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:http/http.dart';
import 'package:intl/intl.dart';
import 'package:nhance_partner/presentation/providers/userRoleProvider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/routing/routes.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../data/utils/validators.dart';
import '../../layouts/main_layout.dart';
import '../../layouts/responsive_layout.dart';
import '../../providers/manager_provider.dart';
import '../../themes/indicators/date_field_theme.dart';
import '../../themes/indicators/export_btn.dart';
import '../../themes/indicators/search_field_theme.dart';
import '../../widgets/custom_Stdate_EnDate_Filter.dart';
import '../../widgets/custom_action_popup.dart';

class EnquiryList extends ConsumerStatefulWidget {
  const EnquiryList({super.key});
  @override
  ConsumerState<EnquiryList> createState() => EnquiryListState();
}

class EnquiryListState extends ConsumerState<EnquiryList> {
  int currentPage = 1;
  int itemsPerPage = 10;
  late ApiService apiService;
  dynamic roleId;
  dynamic userId;
  dynamic SelectedStatus;
  dynamic SelectedStaffId;
  late final String? selectedStatusVal;
  final _formKey = GlobalKey<FormState>();

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

  bool isLoading = false;
  Map<String, TextEditingController> controllers = {};
  List<String> tabHeader = ['startDate', 'endDate'];

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

    apiService = ApiService();

    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }

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

      print("A56 => r : $roleId | mId: $id | uId: $userId ");

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

  void filterDateRange1() {
    print("filterDateRange");
    // if (!_formKey.currentState!.validate()) return;

    // final fromDate = controllers['startDate']?.text ?? '';
    // final toDate = controllers['endDate']?.text ?? '';
    print("filterDateRange1");
    // Call with selected dates
    getStaffList(userId, roleId);
  }

  void filterDateRange() {
    print('SelectedStatus - $SelectedStatus');
    getStaffList(userId, roleId);
  }

  Future<void> refrshfilterDateRange() async {
    // 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();
    // });
    getStaffList(userId, roleId);
  }

  // Future<void> getStaffList(int managerId, role) async {
  //   print('A72 => Fns called => $managerId | $role');
  //   setState(() {
  //     isLoading = true;
  //   });
  //
  //   try {
  //     final response = await apiService.fetchEnquiryList(managerId, role);
  //
  //     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('A82 => getStaffListData => ${response['data']}');
  //       setState(() {
  //         controllers['startDate']?.text = fromDate;
  //         controllers['endDate']?.text = toDate;
  //         if (data is List) {
  //           // Already a list of maps
  //           getStaffData = List<Map<String, dynamic>>.from(data);
  //         } else if (data is Map) {
  //           // Single object, wrap in a list
  //           getStaffData = [Map<String, dynamic>.from(data)];
  //         } else {
  //           getStaffData = [];
  //         }
  //         // getStaffData = List<Map<String, dynamic>>.from(response['data']);
  //         originalData = getStaffData;
  //         filteredData = List.from(originalData);
  //         // print('originalData - $getClaimPolicies');
  //       });
  //     } else {
  //       getStaffData = [];
  //       originalData = [];
  //     }
  //   } catch (e) {
  //     print('Exception occurred: $e');
  //   } finally {
  //     setState(() {
  //       isLoading = false;
  //     });
  //   }
  // }

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

    dynamic fromDt;
    dynamic toDt;

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

    if (fromDateVal == '' && toDateVal == '') {
      print("ENQ LIST PAGE");

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

      print('Enq FROM TO - $fromDt - $toDt');
    } else {
      fromDt = fromDateVal;
      toDt = toDateVal;
    }

    print("ASSS= $SelectedStatus");
    try {
      final response = await apiService.fetchEnquiryList(
        managerId,
        userId,
        role,
        fromDate: fromDt,
        toDate: toDt,
        selectedStatus: SelectedStatus != null ? 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');

        setState(() {
          controllers['startDate']?.text = fromDate;
          controllers['endDate']?.text = toDate;
          if (data is List) {
            getStaffData = List<Map<String, dynamic>>.from(data);
          } 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(() {
        isLoading = false;
      });
    }
  }

  List<dynamic> get _paginatedData1 {
    // Sort descending by id first
    final sortedData = [...filteredData]
      ..sort((a, b) => int.parse(b['id']) - int.parse(a['id']));

    final startIndex = (currentPage - 1) * itemsPerPage;
    final endIndex = (currentPage * itemsPerPage).clamp(0, sortedData.length);

    return sortedData.sublist(startIndex, endIndex);
  }

  List<dynamic> get _paginatedData {
    // Sort descending by id first
    final sortedData = [...filteredData]
      ..sort((a, b) => int.parse(b['id']) - int.parse(a['id']));

    if (sortedData.isEmpty) return [];

    // Ensure currentPage is valid
    final maxPage = (sortedData.length / itemsPerPage).ceil();
    final safePage = currentPage.clamp(1, maxPage);

    final startIndex = (safePage - 1) * itemsPerPage;
    final endIndex = (startIndex + itemsPerPage).clamp(0, sortedData.length);

    return sortedData.sublist(startIndex, endIndex);
  }

  Future<void> handleEdit(item) async {
    // Navigator.pop(context);
    print('EDITStaff - ${item['id']}');
    // dynamic id = data['id'];
    // context.go('/tabEnquiry/$id');

    final prefs = await SharedPreferences.getInstance();

    // ✅ Remove old value (if any)
    await prefs.remove('enqAgentDataId');

    // setState(() {
    final id = item['id'].toString();
    // ✅ Save the new id
    await prefs.setString('enqAgentDataId', id.toString());
    ref.read(enquiryIdProvider.notifier).state = id;

    // });
    // update provider

    context.go(AppRoutes.tabEnquiry);
  }

  void filterData(String query) {
    print("FilterDAta - $query");
    setState(() {
      filteredData = getStaffData.where((item) {
        // final isActiveStatus = item['is_active'] == "1" ? "active" : "inactive";

        return (_formatDate(item['enquiry_created_on']) ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (_formatDate(item['updated_on']) ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['reg_no'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['insurer_name'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['status'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['remarks'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            );
      }).toList();
    });
  }

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

  List<Widget> _buildPopupMenuActions(BuildContext context, dynamic data) {
    return [
      GestureDetector(
        onTap: () {
          Navigator.pop(context);
          print('EDITStaff - ${data['id']}');
          // dynamic id = data['id'];
          // context.go('/tabEnquiry/$id');
          setState(() {
            final id = data['id'].toString();
            ref.read(enquiryIdProvider.notifier).state = id;
          });
          // update provider

          context.go(AppRoutes.tabEnquiry);
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.edit_sharp, color: Color(0xFF319718), size: 18),
            SizedBox(width: 10),
            Text('Edit'),
          ],
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      title: "Enquiry",
        body: SelectionArea(
          child: Container(
        // color: Colors.yellow.shade50,
        width: MediaQuery.of(context).size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              height: 30,
              width: MediaQuery.of(context).size.width,
              child: GestureDetector(
                onTap: () {
                  context.go(AppRoutes.dashboard);
                },
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    // Icon(
                    //   Icons.arrow_left_sharp,
                    //   size: ResponsiveLayout.isMobile(context) ? 25 : 35,
                    //   color: Color(0xFF425B5B),
                    // ),
                    Tooltip(
                      message: 'Back',
                      child: IconButton(
                        icon: Icon(
                          Icons.arrow_left_sharp,
                          size: ResponsiveLayout.isMobile(context) ? 25 : 25,
                          color: const Color(0xFF425B5B),
                        ),
                        onPressed: () {
                          context.go(AppRoutes.dashboard);
                        },
                        splashRadius: 18,
                        hoverColor: Colors.black12,
                        padding: const EdgeInsets.all(4),
                        constraints: const BoxConstraints(),
                      ),
                    ),
                    const SizedBox(width: 5), // spacing between icon and text
                    Text(
                      "Enquiries ",
                      style: GoogleFonts.inter(
                        fontSize: ResponsiveLayout.isMobile(context) ? 14 : 18,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: ResponsiveLayout.isMobile(context) ? 5 : 5),
            ResponsiveLayout.isMobile(context)
                ? Container(
                    height: MediaQuery.of(context).size.height * 0.7,
                    child: SingleChildScrollView(
                      child: Padding(
                        padding: EdgeInsets.all(8),
                        child: _buildContent(context),
                      ),
                    ),
                  )
                : Expanded(
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      padding: EdgeInsets.all(8.0),
                      child: _buildContent(context),
                    ),
                  ),

            Container(
              // height: 20,
              width: MediaQuery.of(context).size.width,
              // color: Colors.green.shade50,
              child: PaginationControls(
                currentPage: currentPage,
                itemsPerPage: itemsPerPage,
                // totalItems: dataVal.length,
                totalItems: filteredData.length,
                // activeColor: layoutColor, // your theme color
                onPageChanged: (page) {
                  setState(() {
                    currentPage = page;
                  });
                },
                onItemsPerPageChanged: (items) {
                  setState(() {
                    itemsPerPage = items;
                    currentPage = 1;
                  });
                },
              ),
            ),
          ],
        ),
      ),
    ));
  }

  Widget _buildContent(BuildContext context) {
    return Column(
      children: [
        if (ResponsiveLayout.isMobile(context)) ...[
          Container(
            padding: EdgeInsets.all(8.0),
            color: Color(0xffD9EBE8),
            child: DateFilterRow(
              key: ValueKey(SelectedStatus ?? ''),
              role: roleId,
              id: userId,
              onFilterStaff: (val) {
                print('Selected Filterd STAFF Id - $val');
                SelectedStaffId = val;
              },
              selectedStaffId: SelectedStaffId,
              selectedStatusVal: SelectedStatus,
              startController: controllers['startDate']!,
              endController: controllers['endDate']!,
              onStatusChanged: (val) {
                SelectedStatus = val; // update parent
                filterDateRange();
              },
              formKey: _formKey,
              isMobile: ResponsiveLayout.isMobile(context),
              onFilter: () {
                // call your filter logic
                filterDateRange();
              },
              onRefresh: () {
                // call your refresh logic
                refrshfilterDateRange();
              },
            ),
          ),
        ],
        if (ResponsiveLayout.isMobile(context)) SizedBox(height: 5),
        Container(
          // height: 40,
          // color: Colors.pink,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              if (!ResponsiveLayout.isMobile(context)) ...[
                DateFilterRow(
                  role: roleId,
                  id: userId,
                  key: ValueKey(SelectedStatus ?? ''),
                  onFilterStaff: (val) {
                    print('Selected Filterd STAFF Id - $val');
                    SelectedStaffId = val;
                  },
                  selectedStaffId: SelectedStaffId,
                  selectedStatusVal: SelectedStatus,
                  startController: controllers['startDate']!,
                  endController: controllers['endDate']!,
                  onStatusChanged: (val) {
                    SelectedStatus = val; // update parent
                  },

                  formKey: _formKey,
                  isMobile: ResponsiveLayout.isMobile(context),
                  onFilter: () {
                    // call your filter logic
                    filterDateRange();
                  },
                  onRefresh: () {
                    // call your refresh logic
                    refrshfilterDateRange();
                  },
                ),

                Spacer(),
              ],

              ThemedSearchField(
                hintText: 'Search',
                backgroundColor: Color(0xFFFFFFFF),
                // backgroundColor: Color(0xFFF6F8F8),
                onChanged: filterData,
                controller: _searchStaffController,
                txtwidth: ResponsiveLayout.isMobile(context)
                    ? MediaQuery.of(context).size.width * 0.6
                    : MediaQuery.of(context).size.width * 0.13,
                txtHeight: 30,
              ),
              ResponsiveLayout.isMobile(context)
                  ? Spacer()
                  : SizedBox(width: 10),

              ExportBtn(
                sheetName: "Enquiry",
                fileName: "enquiry_list",
                data: filteredData,
                txt: !ResponsiveLayout.isMobile(context) ? true : false,

                // headers: [],
                displayHeaders: [
                  "S.No.",
                  // "Received Date & Time",
                  "Received Date",
                  "Vehicle.No.",
                  "Insurer",
                  "Updated Date",
                  "Status",
                  "Remarks",
                ],
                keys: [
                  "sno", // handled internally as i + 1
                  // "created_on",
                  "enquiry_created_on",
                  "reg_no",
                  "insurer_name",
                  "updated_on",
                  "status",
                  "remarks",
                ],
                // headers: [
                //   "id",
                //   "created_on",
                //   "updated_on",
                //   "reg_no",
                //   "insurer_name",
                //   "status",
                //   "remarks",
                // ],
              ),

              SizedBox(width: 10),
              GestureDetector(
                onTap: () async {
                  final prefs = await SharedPreferences.getInstance();

                  await prefs.remove('enqAgentDataId');
                  ref.read(enquiryIdProvider.notifier).state = null;
                  context.go(AppRoutes.tabEnquiry);
                  // print('Export');
                },
                child: Container(
                  padding: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    color: const Color(0xFF2E7D6E),
                    // color: Color(0xFF425B5B),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Tooltip(
                        message: 'Raise Enquiry',
                        child: Icon(Icons.add, color: Colors.white, size: 18),
                      ),

                      if (!ResponsiveLayout.isMobile(context)) ...[
                        // SizedBox(width: 10),
                        // Text(
                        //   'Raise Enquiry',
                        //   style: GoogleFonts.inter(
                        //     color: Colors.white,
                        //     fontWeight: FontWeight.w600,
                        //     fontSize: 14,
                        //   ),
                        // ),
                        // GestureDetector(
                        //   onTap: () {
                        //     ref
                        //             .read(
                        //               enquiryIdProvider.notifier,
                        //             )
                        //             .state =
                        //         null;
                        //     context.go(AppRoutes.tabEnquiry);
                        //   },
                        //   child: Text(
                        //     'Create New Enquiry',
                        //     style: GoogleFonts.inter(
                        //       color: Colors.white,
                        //       fontWeight: FontWeight.w600,
                        //       fontSize: 14,
                        //     ),
                        //   ),
                        // ),
                      ],
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 10),

        if (!ResponsiveLayout.isMobile(context))
          Container(
            decoration: BoxDecoration(
              // color: Color(0xFFEDF6F5),
              color: Color(0xFFF1F5F9),
              borderRadius: BorderRadius.circular(6),
            ),
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Row(
              children: [
                Expanded(flex: 1, child: Text('S.No.', style: _headerStyle)),
                Expanded(
                  flex: 3,
                  child: Text('Received Date', style: _headerStyle),
                  // child: Text('Enquiry Created Date', style: _headerStyle),
                ),

                Expanded(
                  flex: 3,
                  child: Text('Vehicle.No.', style: _headerStyle),
                ),
                Expanded(flex: 3, child: Text('Insurer', style: _headerStyle)),
                Expanded(
                  flex: 3,
                  child: Text('Updated Date', style: _headerStyle),
                ),
                Expanded(flex: 3, child: Text('Status', style: _headerStyle)),
                Expanded(flex: 2, child: Text('Remarks', style: _headerStyle)),
                Expanded(flex: 1, child: Text('Action', style: _headerStyle)),
              ],
            ),
          ),

        ResponsiveLayout.isMobile(context)
            ? _buildDataTable(context)
            : Expanded(child: _buildDataTable(context)),
      ],
    );
  }

  // Widget _buildDataTable1(BuildContext context) {
  //   if (filteredData.isEmpty) {
  //     return const SizedBox(
  //       height: 50,
  //       child: Center(child: Text('No available data')),
  //     );
  //   }
  //
  //   final sortedData = [..._paginatedData];
  //   return ListView.builder(
  //     itemCount: ResponsiveLayout.isMobile(context)
  //         ? sortedData
  //               .length // only cards for mobile
  //         : sortedData.length + 1, // +1 for header in desktop
  //     itemBuilder: (context, index) {
  //       if (!ResponsiveLayout.isMobile(context) && index == 0) {
  //         return _buildHeader();
  //       }
  //
  //       final startIndex = (currentPage - 1) * itemsPerPage;
  //       final item =
  //           sortedData[index - (ResponsiveLayout.isMobile(context) ? 0 : 1)];
  //       final sno = startIndex + index;
  //
  //       return !ResponsiveLayout.isMobile(context)
  //           ? _buildDataRow(item, sno)
  //           : _buildDataCard(item, sno);
  //     },
  //   );
  // }

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

    final sortedData = [..._paginatedData];

    if (ResponsiveLayout.isMobile(context)) {
      // Use Column instead of ListView
      return Column(
        children: List.generate(sortedData.length, (index) {
          final startIndex = (currentPage - 1) * itemsPerPage;
          final item = sortedData[index];
          final sno = startIndex + index;
          return _buildDataCard(item, sno);
        }),
      );
    }

    // Desktop: keep ListView.builder
    return ListView.builder(
      itemCount: sortedData.length + 1,
      itemBuilder: (context, index) {
        if (index == 0) return _buildHeader();
        final startIndex = (currentPage - 1) * itemsPerPage;
        final item = sortedData[index - 1];
        final sno = startIndex + index;
        return _buildDataRow(item, sno);
      },
    );
  }

  Widget _buildHeader() {
    return SizedBox.shrink();
  }

  Widget _buildDataRow(Map<String, dynamic> item, sno) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 16),
      // margin: const EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: Colors.white,

        // color: Color(0xFFE0F7F9),
        border: const Border(
          bottom: BorderSide(color: Color(0xFFEAEAEA), width: 1),
        ),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(flex: 1, child: Text('$sno' ?? '-', style: _dataBold)),
          Expanded(
            flex: 3,
            child: Text(
              _formatDate(item['enquiry_created_on']) ?? '-',
              style: _dataBold,
            ),
          ),

          Expanded(
            flex: 3,
            child: Text(item['reg_no'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 3,
            child: Text(
              item['insurer_name'] ?? '-',
              // (item['insurer_name'] ?? '').length > 10
              //     ? '${item['insurer_name'].substring(0, 10)}...'
              //     : item['insurer_name'] ?? '',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(
              _formatDate(item['updated_on']) ?? '-',
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(item['status'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 2,
            child: Text(
              // item['remarks'] ?? '-',
              (item['remarks'] ?? '').length > 10
                  ? '${item['remarks'].substring(0, 10)}...'
                  : item['remarks'] ?? '',
              style: _dataBold,
              // softWrap: true,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ),

          Expanded(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  // GestureDetector(
                  // onTap: () {
                  //   Navigator.pop(context);
                  //   print('EDITStaff - ${item['id']}');
                  //   // dynamic id = data['id'];
                  //   // context.go('/tabEnquiry/$id');
                  //   setState(() {
                  //     final id = item['id'].toString();
                  //     ref.read(enquiryIdProvider.notifier).state = id;
                  //   });
                  //   // update provider
                  //
                  //   context.go(AppRoutes.tabEnquiry);
                  // },
                  // onTap: () {
                  //   handleEdit(item);
                  // },
                  // child: Image.asset(
                  //   "assets/miscellaneous/Edit.png",
                  //   height: 15,
                  //   width: 15,
                  // ),
                  // ),
                  Tooltip(
                    message: 'Edit',
                    child: IconButton(
                      icon: Image.asset(
                        "assets/miscellaneous/Edit.png",
                        height: 12,
                        width: 15,
                      ),
                      onPressed: () {
                        handleEdit(item);
                      },
                      splashRadius: 18,
                      hoverColor: Colors.black12,
                      padding: const EdgeInsets.all(8),
                      constraints: const BoxConstraints(),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // Expanded(
          //   flex: 1,
          //   child: Row(
          //     children: [
          //       PopupMenuButton<int>(
          //         color: Colors.white,
          //         padding: EdgeInsets.zero,
          //         offset: Offset(0, 30),
          //         icon: Icon(
          //           Icons.more_vert,
          //           color: Color(0xFF475569),
          //           size: 14,
          //         ),
          //         itemBuilder: (context) => [
          //           CustomPopupMenuEntry(
          //             child: Container(
          //               padding: EdgeInsets.symmetric(
          //                 horizontal: 8,
          //                 vertical: 8,
          //               ),
          //               child: Column(
          //                 mainAxisSize: MainAxisSize.min,
          //                 mainAxisAlignment: MainAxisAlignment.center,
          //                 children: _buildPopupMenuActions(context, item),
          //               ),
          //             ),
          //           ),
          //         ],
          //       ),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  Widget _buildDataCard(Map<String, dynamic> item, int sno) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xFFF6FEFD),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: const Color(0xffD9EBE8)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item['reg_no'] ?? '-', style: _headerStyle),
              Tooltip(
                message: 'Edit',
                child: IconButton(
                  icon: Image.asset(
                    "assets/miscellaneous/Edit.png",
                    height: 15,
                    width: 15,
                  ),
                  onPressed: () {
                    handleEdit(item);
                  },
                  splashRadius: 28,
                  hoverColor: Colors.black12,
                  padding: const EdgeInsets.all(8),
                  constraints: const BoxConstraints(),
                ),
              ),
              // GestureDetector(
              //   // onTap: () {
              //   //   Navigator.pop(context);
              //   //   print('EDITStaff - ${item['id']}');
              //   //   // dynamic id = data['id'];
              //   //   // context.go('/tabEnquiry/$id');
              //   //   setState(() {
              //   //     final id = item['id'].toString();
              //   //     ref.read(enquiryIdProvider.notifier).state = id;
              //   //   });
              //   //   // update provider
              //   //
              //   //   context.go(AppRoutes.tabEnquiry);
              //   // },
              //   onTap: () {
              //     handleEdit(item);
              //   },
              //   child: Image.asset(
              //     "assets/miscellaneous/Edit.png",
              //     height: 15,
              //     width: 15,
              //   ),
              // ),
              // PopupMenuButton<int>(
              //   color: Colors.white,
              //   padding: EdgeInsets.zero,
              //   offset: Offset(0, 30),
              //   icon: Icon(Icons.more_vert, color: Color(0xFF475569), size: 14),
              //   itemBuilder: (context) => [
              //     CustomPopupMenuEntry(
              //       child: Container(
              //         padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
              //         child: Column(
              //           mainAxisSize: MainAxisSize.min,
              //           mainAxisAlignment: MainAxisAlignment.center,
              //           children: _buildPopupMenuActions(context, item),
              //         ),
              //       ),
              //     ),
              //   ],
              // ),
            ],
          ),
          const Divider(color: Color(0xffD9EBE8), thickness: 0.8),

          // Company + Vehicle Reg No
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,

                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text("Insurer", style: _cardheaderStyle),
                    Text(
                      item['insurer_name'] ?? '-',
                      style: _cardBodyStyle,
                      maxLines: 3,
                      softWrap: true,
                    ),
                  ],
                ),
              ),
              SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text("Status", style: _cardheaderStyle),
                    Text(
                      item['status'] ?? '-',
                      style: _cardBodyStyle,
                      maxLines: 2,
                      softWrap: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),

          // Created On + Remarks
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Received Date', style: _cardheaderStyle),
                    // Text("Received Date & Time", style: _cardheaderStyle),
                    Text(
                      _formatDate(item['enquiry_created_on']) ?? '-',
                      style: _cardBodyStyle,
                    ),
                  ],
                ),
              ),
              SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Remarks", style: _cardheaderStyle),
                    Text(
                      item['remarks'] ?? '-',
                      style: _cardBodyStyle,
                      maxLines: 3,
                      softWrap: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget buildStartDate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Start Date', style: _textStyle),
        SizedBox(height: 5),
        ThemedDateField(
          hintText: "Select Date",
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.16,
          // txtheight: 50,
          // backgroundColor: const Color(0xFFECECEC),
          // validator: (value) => Validators.requiredField(value, "date"),
          controller: controllers['startDate']!,
          onDateSelected: (date) {
            print("SPicked Date: $date");

            controllers['startDate']?.text = DateFormat(
              'dd-MM-yyyy',
            ).format(date);
            //  controllers['date']?.text = date as String;
          },
        ),
      ],
    );
  }

  Widget buildEndDate(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('End Date', style: _textStyle),
        SizedBox(height: 5),
        ThemedDateField(
          hintText: "Select Date",
          txtwidth: ResponsiveLayout.isMobile(context)
              ? null
              : MediaQuery.of(context).size.width * 0.16,
          // txtheight: 50,
          // backgroundColor: const Color(0xFFECECEC),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return "End Date is required";
            }

            final fromText = controllers['startDate']?.text ?? '';
            if (fromText.isNotEmpty) {
              final startDate = DateFormat('dd-MM-yyyy').parse(fromText);
              final endDate = DateFormat('dd-MM-yyyy').parse(value);

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

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

    fontWeight: FontWeight.w400,
    color: Color(0xFF000000),
  );

  static final _dataSub = GoogleFonts.inter(
    fontSize: 10,
    fontWeight: FontWeight.w300,
    color: Color(0xFF585757),
  );

  // static const _headerStyle = GoogleFonts.inter(
  //   color: Colors.black,
  //   fontWeight: FontWeight.bold,
  // );
  // static final _headerStyle = GoogleFonts.inter(
  //   color: Colors.black,
  //   fontWeight: FontWeight.bold,
  // );

  static final _headerStyle = GoogleFonts.poppins(
    fontSize: 11.2,
    fontWeight: FontWeight.w500,
    color: Color(0xFF1E293B),
  );
  static final _cardheaderStyle = GoogleFonts.inter(
    color: Colors.black,
    fontWeight: FontWeight.w600,
    fontSize: 12,
  );

  static final _cardBodyStyle = GoogleFonts.inter(
    color: Color(0xFF545454),
    fontWeight: FontWeight.w400,
    fontSize: 12,
  );

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