import 'package:file_picker/file_picker.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/providers/userRoleProvider.dart';
import 'package:nhance_partner/presentation/screens/staff/assignStaff.dart';
import '../../../../core/routing/routes.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../../data/utils/toastNotification.dart';
import '../../../layouts/main_layout.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';
import '../../../providers/quotation_staff_proivder.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';
import '../../Enquiry/enquiry/policy_popup.dart';
import '../../Enquiry/policy_claims_endros/sub_claims.dart';
// import '../../../../data/utils/toastNotification.dart';

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

class policylistState extends ConsumerState<policylist> {
  int currentPage = 1;
  int itemsPerPage = 10;
  late ApiService apiService;
  dynamic userId;
  dynamic managerId;
  dynamic SelectedStatus;
  dynamic SelectedInsurer;
  dynamic SelectedStaffId;
  // List<Map<String, dynamic>> dataVal = [];
  List<Map<String, dynamic>> getStaffData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];
  List<Map<String, dynamic>> excelResponseData = [];
  List<Map<String, dynamic>> auditHistoryResponseData = [];
  bool isLoading = false;
  dynamic roleId;
  final _formKey = GlobalKey<FormState>();
  Map<String, TextEditingController> controllers = {};
  List<String> tabHeader = ['startDate', 'endDate'];
  dynamic choosedPolcyId;
  PlatformFile? docPDFUploadedFile;
  String? selectedPDFFileNames;
  late ProviderSubscription<bool> refreshSub;

  @override
  void initState() {
    super.initState();
    SelectedStatus = 'All';
    SelectedInsurer = '';
    apiService = ApiService();

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

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

      SelectedStatus = (roleId == 'Accounts') ? 'Not Verified' : 'All';
      print("D74 => r : $roleId | mId: $managerId | uId: $userId ]'-'[ SS : $SelectedStatus ");
      if (userId != null) {
        getStaffList(managerId!, userId, roleId , selectedStatus : SelectedStatus);
      }

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

          // callRefresh();
          print("D87 => r : $roleId | mId: $managerId | uId: $userId ]'-'[ SS : $SelectedStatus ");
          getStaffList(managerId!, userId, roleId,selectedStatus : SelectedStatus);
          ref.read(policyDataAcurancyRefreshProvider.notifier).state = false;
        }
      });
    });
  }

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

    SelectedStatus = (roleId == 'Accounts') ? 'Not Verified' : 'All';
    print("D100 => r : $roleId | mId: $managerId | uId: $userId ]'-'[ SS : $SelectedStatus ");
    if (userId != null) {
      getStaffList(managerId, userId, roleId,selectedStatus : SelectedStatus);
    }
  }

  Future<void> getStaffList(
    int managerId,
    id,
    role, {
    String fromDate = '',
    String toDate = '',
        String selectedStatus = 'All',
        String selectedInsurer = '',
  }) async {
    print('D68 => Fns called => $managerId | $role');
    setState(() {
      isLoading = true;
    });
    dynamic fromDt;
    dynamic toDt;
    final dateFormat = DateFormat('dd-MM-yyyy');
    final today = DateTime.now();
    final fromDateVal = controllers['startDate']?.text ?? '';
    final toDateVal = controllers['endDate']?.text ?? '';

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

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

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

    try {
      final response = await apiService.fetchPolicyDataOnlyList(
        managerId,
        id,
        role,
        fromDate: fromDt,
        toDate: toDt,
        selectedStaffId: SelectedStaffId ?? '',
          selectedStatus:selectedStatus,
          selectedInsurer:selectedInsurer
      );

      if (response['status'] == 'success') {
        final data = response['data'];
        print('D81 => getStaffListData => ${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) {
            // 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;
      });
    }
  }

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

  void filterDateRange() {
    print('filterDateRange');
    // ✅ Validate the form first
    // if (!_formKey.currentState!.validate()) {
    //   // stop execution if validation fails
    //   return;
    // }
    //
    // final fromDateText = controllers['startDate']?.text ?? '';
    // final toDateText = controllers['endDate']?.text ?? '';
    //
    // // Optional: double-check End >= Start
    // final fromDate = DateFormat('dd-MM-yyyy').parse(fromDateText);
    // final toDate = DateFormat('dd-MM-yyyy').parse(toDateText);
    //
    // if (toDate.isBefore(fromDate)) {
    //   // This is already caught by the validator, but extra safety
    //   ScaffoldMessenger.of(context).showSnackBar(
    //     SnackBar(content: Text("End Date cannot be earlier than Start Date")),
    //   );
    //   return;
    // }

    // ✅ Call your API
    // getStaffList(managerId, userId, roleId);

    // print("D61 => r : $roleId | mId: $id | uId: $userId");
    if (userId != null && managerId != null) {
      print('filterDateRange 1s');
      print('manager - $managerId - userID -$userId - roledId -$roleId');

      getStaffList(managerId!, userId, roleId, selectedStatus : SelectedStatus ?? 'All', selectedInsurer:SelectedInsurer??'');
    }
    print('filterDateRange 1');
  }

  void refrshfilterDateRange() {
    setState(() {
      SelectedStaffId = null;
      controllers['startDate']!.clear();
      controllers['endDate']!.clear();
      SelectedStatus = (roleId == 'Accounts') ? 'Not Verified' : 'All'; // ✅
      SelectedInsurer = '';
      controllers['startDate']?.text = '';
      controllers['endDate']?.text = '';
      // Reset the FormField validation
      _formKey.currentState?.reset();
    });
    getStaffList(managerId, userId, roleId, selectedStatus : SelectedStatus ?? 'All',selectedInsurer:SelectedInsurer??'');
  }

  void filterData(String query) {
    print("FilterDAta - $query");

    final lowerQuery = query.toLowerCase();

    setState(() {
      filteredData = getStaffData.where((item) {
        // ⭐ Compute UI status text
        final accuracyText = item['is_data_accuracy_checked'] == '1'
            ? 'Verified'
            : 'Click to Verify';

        return (item['agent_name'] ?? '-').toLowerCase().contains(lowerQuery) ||
            (item['agent_code'] ?? '-').toLowerCase().contains(lowerQuery) ||
            (item['reg_no'] ?? '-').toLowerCase().contains(lowerQuery) ||
            (item['insurer_name'] ?? '-').toLowerCase().contains(lowerQuery) ||
            (item['insurer_short_name'] ?? '-').toLowerCase().contains(
              lowerQuery,
            ) ||
            (item['assigned_to_name'] ?? '-').toLowerCase().contains(
              lowerQuery,
            ) ||
            (item['insured_name'] ?? '-').toLowerCase().contains(lowerQuery) ||
            (item['premium_amount'] ?? '-').toLowerCase().contains(
              lowerQuery,
            ) ||
            (item['payment_mode_value'] ?? '-').toLowerCase().contains(
              lowerQuery,
            ) ||
            (_formatDate(item['updated_on']) ?? '-').toLowerCase().contains(
              lowerQuery,
            ) ||
            (item['policy_number'] ?? '-').toLowerCase().contains(lowerQuery) ||
            // ⭐ NEW CONDITIONS for search
            accuracyText.toLowerCase().contains(lowerQuery);
      }).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
    }
  }

  Future<void> fetchPolicyExcelReport() async {
    final String fromDate = controllers['startDate']!.text; // "11-01-2025"
    final String toDate = controllers['endDate']!.text; // "20-01-2025"
    final String searchValue = _searchStaffController.text;
    final response = await apiService.generatePolicyExcel(
      managerId,
      fromDate,
      toDate,
      searchValue,
         SelectedStatus ?? 'All',
        SelectedInsurer ?? '',
    );
    // Map your controllers and IDs to the API parameters
    // final String fromDate = controllers['startDate']!.text; // "11-01-2025"
    // final String toDate = controllers['endDate']!.text;     // "20-01-2025"
    // print("fetchPolicyExcelReport function called here.");
    //
    // try {
    //   // Assuming you have a generic _makeGetRequest method
    //   final response = await apiService.fetchPolicyExcel(managerId,fromDate,toDate);
    //
    //   if (response != null && response['status'] == 200) {
    //     setState(() {
    //       // Store the list of data in your variable
    //       excelResponseData = response['data'];
    //     });
    //     print("Data fetched. Ready to export.");
    //   }
    // } catch (e) {
    //   debugPrint("Export Error: $e");
    //   print("Failed to fetch report data.");
    // }
  }

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      title: "Policy",
      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: [
                    Text(
                      "Policy",
                      style: GoogleFonts.poppins(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 5),

            ResponsiveLayout.isMobile(context)
                ? Container(
                    height: MediaQuery.of(context).size.height * 0.69,
                    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(
              dataFrom: 'Policy',
              role: roleId,
              id: userId,
              onFilterStaff: (val) {
                print('Selected Filterd STAFF Id - $val');
                SelectedStaffId = val;
              },
              selectedStaffId: SelectedStaffId,
              startController: controllers['startDate']!,
              endController: controllers['endDate']!,
              selectedStatusVal: SelectedStatus,
              selectedInsurerVal : SelectedInsurer,
              onStatusChanged: (val) {
                setState(() {
                  SelectedStatus = val; // update parent
                });
              },
              onInsurerChanged: (val) {
                setState(() {
                  SelectedInsurer = val; // update parent
                });
              },
              formKey: _formKey,
              isMobile: ResponsiveLayout.isMobile(context),
              onFilter: () {
                // call your filter logic
                filterDateRange();
              },
              onRefresh: () {
                // call your refresh logic
                refrshfilterDateRange();
              },
            ),
          ),
        ],

        Container(
          // height: 40,
          // color: Colors.pink,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              if (!ResponsiveLayout.isMobile(context)) ...[
                DateFilterRow(
                  dataFrom: 'Policy',
                  role: roleId,
                  id: userId,
                  onFilterStaff: (val) {
                    print('Selected Filterd STAFF Id - $val');
                    SelectedStaffId = val;
                  },
                  selectedStaffId: SelectedStaffId,
                  startController: controllers['startDate']!,
                  endController: controllers['endDate']!,
                  selectedStatusVal: SelectedStatus,
                  selectedInsurerVal : SelectedInsurer,
                  onStatusChanged: (val) {
                    setState(() {
                      SelectedStatus = val; // update parent
                    });
                  },
                  onInsurerChanged: (val) {
                    setState(() {
                      SelectedInsurer = val; // update parent
                    });
                  },
                  formKey: _formKey,
                  isMobile: ResponsiveLayout.isMobile(context),
                  onFilter: () {
                    print('onFilter');
                    // call your filter logic
                    filterDateRange();
                  },
                  onRefresh: () {
                    // call your refresh logic
                    refrshfilterDateRange();
                  },
                ),

                Spacer(),
              ],
              ResponsiveLayout.isMobile(context)
                  ? SizedBox(height: 10)
                  : SizedBox.shrink(),
              ThemedSearchField(
                hintText: 'Search',

                // backgroundColor: Color(0xFFF6F8F8),
                onChanged: filterData,
                controller: _searchStaffController,
                backgroundColor: Color(0xFFFFFFFF),
                txtHeight: 30,
                txtwidth: ResponsiveLayout.isMobile(context)
                    ? MediaQuery.of(context).size.width * 0.7
                    : MediaQuery.of(context).size.width * 0.15,
              ),
              ResponsiveLayout.isMobile(context)
                  ? Spacer()
                  : SizedBox(width: 10),
              // ExportBtn(
              //   sheetName: "Policy",
              //   fileName: "Policy_list",
              //   data: filteredData,
              //   txt: !ResponsiveLayout.isMobile(context) ? true : false,
              //   displayHeaders: [
              //     // "Received Date & Time",
              //     "Assigned To",
              //     "Partner",
              //
              //     "Insurer",
              //     "Vehicle.No.",
              //     "Insured Name",
              //     "Premium",
              //     "Payment Mode",
              //     "Policy Number",
              //   ],
              //   keys: [
              //     // "updated_on",
              //     "assigned_to_name",
              //     "agent_name",
              //     "insurer_short_name",
              //     "reg_no",
              //     "insured_name",
              //     "premium_amount",
              //     "payment_mode_value",
              //     "policy_number",
              //   ],
              // ),
              // SizedBox(width: 10),
              Tooltip(
                message: 'Export Excel',
                child: InkWell(
                  onTap: () async {
                    await fetchPolicyExcelReport();
                  },
                  child: Container(
                    padding: const EdgeInsets.all(7.0),
                    decoration: BoxDecoration(
                      color: const Color(0xFF2E7D6E),
                      // color: const Color(0xFF425B5B),
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(
                          "assets/miscellaneous/export.png",
                          height: 13,
                          width: 13,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(width: 10),
            ],
          ),
        ),
        SizedBox(height: 5),
        if (!ResponsiveLayout.isMobile(context))
          Container(
            decoration: BoxDecoration(
              color: Color(0xFFF1F5F9),
              // color: Color(0xFFEDF6F5),
              borderRadius: BorderRadius.circular(6),
            ),
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Row(
              children: [
                // Expanded(
                //   flex: 2,
                //   child: Text('Recieved Date', style: _headerStyle),
                // ),
                Expanded(
                  flex: 3,
                  child: Text('Assigned To', style: _headerStyle),
                ),

                Expanded(flex: 3, child: Text('Partner', style: _headerStyle)),
                Expanded(flex: 2, child: Text('Insurer', style: _headerStyle)),

                Expanded(
                  flex: 2,
                  child: Text('Vehicle No ', style: _headerStyle),
                ),
                Expanded(
                  flex: 3,
                  child: Text('Insured Name', style: _headerStyle),
                ),
                Expanded(flex: 2, child: Text('Premium', style: _headerStyle)),
                Expanded(
                  flex: 2,
                  child: Text('Payment Mode', style: _headerStyle),
                ),
                Expanded(
                  flex: 3,
                  child: Text('Policy Number', style: _headerStyle),
                ),
                Expanded(
                  flex: 2,
                  child: Text('BDS Pushed', style: _headerStyle),
                ),

                Expanded(flex: 3, child: Text('Action', style: _headerStyle)),
              ],
            ),
          ),

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

  // Widget _buildDataTable(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) {
    print('ITEMS $item');
    final String policyId = item['policy_id']?.toString() ?? '';
    final String? pdfPath = item["policy_pdf_file_name"];
    String? fileName = pdfPath != null && pdfPath.isNotEmpty
        ? pdfPath.split('/').last
        : null;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 10, 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: 2,
          //   child: Text(
          //     _formatDate(item['updated_on']) ?? '-',
          //     style: _dataBold,
          //     softWrap: true,
          //     maxLines: 3,
          //   ),
          // ),
          Expanded(
            flex: 3,
            child: Text(item['assigned_to_name'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 3,
            // child: Text(item['agent_name'] ?? '-', style: _dataBold),
            child: Text(
              (item['agent_code'] != null && item['agent_name'] != null)
                  ? '${item['agent_code']} - ${item['agent_name']}'
                  : (item['agent_name'] ?? '-'),
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['insurer_short_name'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(item['reg_no'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 3,
            child: Text(
              item['insured_name'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['premium_amount'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['payment_mode_value'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(
              item['policy_number'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['is_bds_pushed'] == '1' ? 'Yes' : 'No',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          // Expanded(
          //   flex: 3,
          //   child: Row(
          //     children: [
          //       Tooltip(
          //         message: 'Download',
          //         // color: Colors.white,
          //         child: Row(
          //           mainAxisSize: MainAxisSize.min,
          //           mainAxisAlignment: MainAxisAlignment.center,
          //           children: [
          //             InkWell(
          //               onTap: () => apiService.downloadFile(
          //                 apiUrl:
          //                     'policy/downloadPolicyFile?policy_id=$policyId&file_type=policy_pdf',
          //                 apiId: policyId,
          //                 localFile: null,
          //                 fileName: fileName,
          //               ),
          //
          //               child: Container(
          //                 padding: const EdgeInsets.symmetric(
          //                   horizontal: 5,
          //                   vertical: 3,
          //                 ),
          //                 decoration: BoxDecoration(
          //                   borderRadius: BorderRadius.circular(5),
          //                   // color: Color(0xFF425B5B),
          //                   // color: const Color(0xFF2E7D6E),
          //                   color: Colors.green,
          //                 ),
          //                 child: Row(
          //                   children: const [
          //                     Icon(
          //                       Icons.download,
          //                       size: 12,
          //                       color: Colors.white,
          //                     ),
          //                   ],
          //                 ),
          //               ),
          //             ),
          //             SizedBox(width: 10),
          //             InkWell(
          //               onTap: () {
          //                 showAuditHistoryModal(context, item['policy_id']);
          //               },
          //               child: Container(
          //                 padding: EdgeInsets.all(5.4),
          //                 decoration: BoxDecoration(
          //                   color: const Color(0xFF2E7D6E),
          //                   // color: Color(0xFF425B5B),
          //                   borderRadius: BorderRadius.circular(8.0),
          //                 ),
          //                 child: Row(
          //                   // mainAxisSize: MainAxisSize.min,
          //                   children: [
          //                     Tooltip(
          //                       message: 'Audit History Information',
          //                       child: Icon(
          //                         Icons.file_open_outlined,
          //                         color: Colors.white,
          //                         size: 12,
          //                       ),
          //                     ),
          //                   ],
          //                 ),
          //               ),
          //             ),
          //           ],
          //         ),
          //       ),
          //       if (roleId == 'Accounts') ...[
          //         const SizedBox(width: 5),
          //         Tooltip(
          //           message: '',
          //           child: InkWell(
          //             onTap: () {
          //               context.push(AppRoutes.policyValidation, extra: item);
          //             },
          //             child: Tooltip(
          //               message: item['is_data_accuracy_checked'] == '1'
          //                   ? 'Verified'
          //                   : 'To Verify',
          //               child: Container(
          //                 width: 30, // ⭐ FIXED WIDTH → Equal in both states
          //                 padding: const EdgeInsets.symmetric(
          //                   horizontal: 8,
          //                   vertical: 4,
          //                 ),
          //                 decoration: BoxDecoration(
          //                   color: item['is_data_accuracy_checked'] == '1'
          //                       ? const Color(0xFF2E7D6E)
          //                       : Colors.redAccent,
          //                   borderRadius: BorderRadius.circular(5),
          //                 ),
          //                 child: Row(
          //                   mainAxisSize: MainAxisSize.min,
          //                   mainAxisAlignment: MainAxisAlignment
          //                       .spaceEvenly, // ⭐ Center content
          //                   children: [
          //                     Icon(
          //                       item['is_data_accuracy_checked'] == '1'
          //                           ? Icons.check_circle
          //                           : Icons.error,
          //                       size: 12,
          //                       color: Colors.white,
          //                     ),
          //                     // const SizedBox(width: 1),
          //                     // Text(
          //                     //   item['is_data_accuracy_checked'] == '1'
          //                     //       ? 'Verified'
          //                     //       : 'To Verify',
          //                     //   style: GoogleFonts.poppins(
          //                     //     color: Colors.white,
          //                     //     fontSize: 10,
          //                     //     fontWeight: FontWeight.w500,
          //                     //   ),
          //                     // ),
          //                   ],
          //                 ),
          //               ),
          //             ),
          //           ),
          //         ),
          //         // New Delete Iconic Button
          //         if (item['is_data_accuracy_checked'] == '1') ...[
          //           const SizedBox(width: 8), // Gap between checkmark and delete
          //           Tooltip(
          //             message: 'Delete',
          //             child: InkWell(
          //               onTap: () => _handleSoftDeleteFromList(item['policy_id'].toString()), // Pass the item here
          //               child: Container(
          //                 width: 30,
          //                 height: 24, // Matches your existing vertical padding feel
          //                 decoration: BoxDecoration(
          //                   color: Colors.red, // Red background
          //                   borderRadius: BorderRadius.circular(5),
          //                 ),
          //                 child: const Icon(
          //                   Icons.delete_outline,
          //                   size: 16,
          //                   color: Colors.white,
          //                 ),
          //               ),
          //             ),
          //           ),
          //         ],
          //       ],
          //     ],
          //   ),
          // ),
          Expanded(
            flex: 3,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [

                // DOWNLOAD
                actionButton(
                  icon: Icons.download,
                  color: Colors.green,
                  tooltip: 'Download',
                  onTap: () => apiService.downloadFile(
                    apiUrl: 'policy/downloadPolicyFile?policy_id=$policyId&file_type=policy_pdf',
                    apiId: policyId,
                    localFile: null,
                    fileName: fileName,
                  ),
                ),

                const SizedBox(width: 8),

                // AUDIT
                actionButton(
                  icon: Icons.file_open_outlined,
                  color: const Color(0xFF2E7D6E),
                  tooltip: 'Audit History',
                  onTap: () {
                    showAuditHistoryModal(context, item['policy_id']);
                  },
                ),

                if (roleId == 'Accounts') ...[

                  const SizedBox(width: 8),

                  // VERIFY / TO VERIFY
                  actionButton(
                    icon: item['is_data_accuracy_checked'] == '1'
                        ? Icons.check_circle
                        : Icons.error,
                    color: item['is_data_accuracy_checked'] == '1'
                        ? const Color(0xFF2E7D6E)
                        : Colors.redAccent,
                    tooltip: item['is_data_accuracy_checked'] == '1'
                        ? 'Verified'
                        : 'To Verify',
                    onTap: () {
                      context.push(AppRoutes.policyValidation, extra: item);
                    },
                  ),

                  // DELETE (only if verified)
                  if (item['is_data_accuracy_checked'] == '0') ...[
                    const SizedBox(width: 8),

                    actionButton(
                      icon: Icons.delete_outline,
                      color: Colors.red,
                      tooltip: 'Delete',
                      onTap: () => _handleSoftDeleteFromList(
                        item['policy_id'].toString(),
                      ),
                    ),
                  ],
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  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: [
          /// Top row: Reg.No + Action menu
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item['reg_no'] ?? '-', style: _headerStyle),
              // 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,
              //           children: _buildPopupMenuActions(
              //             context,
              //             item,
              //             item['id'],
              //             item['reg_no'],
              //           ),
              //         ),
              //       ),
              //     ),
              //   ],
              // ),
            ],
          ),
          const Divider(color: Color(0xffD9EBE8), thickness: 0.8),

          /// Company + Status
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Insurer", style: _cardheaderStyle),
                    Text(item['insurer_name'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
              // const SizedBox(width: 5),
              // Expanded(
              //   child: Column(
              //     crossAxisAlignment: CrossAxisAlignment.start,
              //     children: [
              //       Text("Status", style: _cardheaderStyle),
              //       Text(item['status'] ?? '-', style: _cardBodyStyle),
              //     ],
              //   ),
              // ),
            ],
          ),
          const SizedBox(height: 15),

          /// Agents + Assigned To
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Partner", style: _cardheaderStyle),
                    Text(item['agent_name'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
              const SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Assigned To", style: _cardheaderStyle),
                    Text(
                      item['assigned_to_name'] ?? '-',
                      style: _cardBodyStyle,
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),

          /// Insured Name + Premium
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Insured Name", style: _cardheaderStyle),
                    Text(item['insured_name'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
              const SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Premium", style: _cardheaderStyle),
                    Text(item['premium_amount'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),

          /// Payment Mode + Policy Number
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Payment Mode", style: _cardheaderStyle),
                    Text(item['payment_mode'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
              const SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Policy Number", style: _cardheaderStyle),
                    Text(item['policy_number'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),

          /// Date + Remarks
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Recieved Date/Time", style: _cardheaderStyle),
                    Text(
                      _formatDate(item['updated_on']) ?? '-',
                      style: _cardBodyStyle,
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Remarks", style: _cardheaderStyle),
                    Text(
                      item['remarks'] ?? '-',
                      style: _cardBodyStyle,
                      maxLines: 3,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget actionButton({
    required IconData icon,
    required Color color,
    required VoidCallback onTap,
    String? tooltip,
  }) {
    return Tooltip(
      message: tooltip ?? '',
      child: InkWell(
        onTap: onTap,
        child: Container(
          width: 26,        //  SIZE MATCH
          height: 22,       //  SIZE MATCH
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(5), // RADIUS
          ),
          child: Icon(
            icon,
            size: 12,       // ICON SIZE
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Future<void> _handleSoftDeleteFromList(String policyId) async {
    // 1. Confirmation Dialog
    bool confirm = await showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text("Confirm Delete"),
        content: const Text("Are you sure you want to remove this policy?"),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text("Cancel")),
          TextButton(
            onPressed: () => Navigator.pop(ctx, true),
            child: const Text("Delete", style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    ) ?? false;

    if (!confirm) return;

    // 2. Start Loading
    setState(() => isLoading = true);

    try {
      final response = await apiService.softDeletePolicyApi(policyId);

      // If status is 'success' or 'not exists' (expired/deleted)
      if (response['status'] == 'success' || response['status'] == 'not exists') {

        ToastHelper.showSuccessToast(
          context,
          response['message']?.toString() ?? 'Policy deleted successfully',
        );

        // 3. Refresh the List using your existing refresh()
        refresh();

      } else {
        // Handle the 'exists' status from your PHP
        ToastHelper.showErrorToast(
          context,
          response['message']?.toString() ?? 'Unable to delete policy',
        );
      }
    } catch (e) {
      ToastHelper.showErrorToast(
        context,
        'Connection Error: ${e.toString()}',
      );
    } finally {
      if (mounted) {
        setState(() => isLoading = false);
      }
    }
  }

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

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

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

  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: const Color(0xFF545454),
    fontWeight: FontWeight.w400,
    fontSize: 12,
  );
}

void showAuditHistoryModal(BuildContext context, dynamic policyId) {
  showDialog(
    context: context,
    builder: (context) => AuditHistoryModal(policyId: policyId), // Pass ID here
  );
}

class AuditHistoryModal extends ConsumerStatefulWidget {
  final dynamic policyId; // Add this
  const AuditHistoryModal({
    super.key,
    required this.policyId,
  }); // Update constructor

  @override
  ConsumerState<AuditHistoryModal> createState() => AuditHistoryModalState();
}

class AuditHistoryModalState extends ConsumerState<AuditHistoryModal> {
  late ApiService apiService;
  bool isLoading = true; // Start with loading true
  List<Map<String, dynamic>> getAuditHistoryData = [];

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

    // Fetch the audit history as soon as the modal opens
    fetchAuditHistory();
  }

  Future<void> fetchAuditHistory() async {
    setState(() => isLoading = true);
    try {
      // Use widget.policyId here!
      final response = await apiService.fetchAuditHistory(
        widget.policyId.toString(),'partner_policy'
      );

      if (response != null && response['status'] == "success") {
        setState(() {
          getAuditHistoryData = List<Map<String, dynamic>>.from(
            response['data'],
          );
        });
      }
    } catch (e) {
      debugPrint("Audit History Error: $e");
    } finally {
      if (mounted) setState(() => isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colors.white,
      content: Container(
        width: MediaQuery.of(context).size.width * 0.55,
        height: MediaQuery.of(context).size.height * 0.7,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  "Audit History",
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Color(0xFF50A398),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Spacer(),
                Tooltip(
                  message: 'Close',
                  child: IconButton(
                    icon: const Icon(
                      Icons.close,
                      size: 18,
                      // color: Color(0xFF425B5B),
                      color: Color(0xFF2E7D6E),
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    splashRadius: 28,
                    hoverColor: Colors.black12,
                    padding: const EdgeInsets.all(8),
                    constraints: const BoxConstraints(),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 5),
            Expanded(
              child: isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : getAuditHistoryData.isEmpty
                  ? const Center(child: Text("No Audit History Data Found"))
                  : SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: SizedBox(
                        width: double.infinity,
                        child: Theme(
                          data: Theme.of(
                            context,
                          ).copyWith(dividerColor: Colors.grey.shade200),
                          child: DataTable(
                            headingRowColor: WidgetStateProperty.all(
                              Color(0xFFF8FAFC),
                            ),
                            columnSpacing: 20,
                            columns: [
                              DataColumn(
                                label: Text(
                                  "Column Name",
                                  style: _headerStyle(),
                                ),
                              ),
                              DataColumn(
                                label: Text("Message", style: _headerStyle()),
                              ),
                              DataColumn(
                                label: Text(
                                  "Changed On",
                                  style: _headerStyle(),
                                ),
                              ),
                              DataColumn(
                                label: Text(
                                  "Changed By",
                                  style: _headerStyle(),
                                ),
                              ),
                            ],
                            // Inside your build method's DataTable
                            rows: getAuditHistoryData.map((data) {
                              return DataRow(
                                cells: [
                                  DataCell(
                                    Text(
                                      data['column_name'] ?? "-",
                                      style: _cellStyle(),
                                    ),
                                  ),
                                  DataCell(
                                    SizedBox(
                                      width: 300, // Give message more width
                                      child: Text(
                                        data['message'] ?? "-",
                                        style: _cellStyle(),
                                        softWrap:
                                            true, // Ensure text wraps to next line
                                      ),
                                    ),
                                  ),
                                  DataCell(
                                    Text(
                                      formatIndianDate(
                                        data['changed_on'] ?? "",
                                      ),
                                      style: _cellStyle(),
                                    ),
                                  ),
                                  DataCell(
                                    Text(
                                      data['changed_by'] ?? "-",
                                      style: _cellStyle(),
                                    ),
                                  ),
                                ],
                              );
                            }).toList(),
                          ),
                        ),
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

// Helper styles to keep code clean
TextStyle _headerStyle() => GoogleFonts.poppins(
  fontSize: 12,
  fontWeight: FontWeight.w600,
  color: Color(0xFF475569),
);

TextStyle _cellStyle() =>
    GoogleFonts.poppins(fontSize: 11, color: Color(0xFF1E293B));

String formatIndianDate(String dateStr) {
  try {
    DateTime dateTime = DateTime.parse(dateStr);
    // Format: Day-Month-Year Hour:Minute AM/PM
    return DateFormat('dd-MM-yyyy hh:mm a').format(dateTime);
  } catch (e) {
    return dateStr; // Fallback to original string if parsing fails
  }
}
