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 '../../../../core/routing/routes.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/utils/Pagination.dart';
import '../../../layouts/main_layout.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';
import '../../../themes/indicators/export_btn.dart';
import '../../../themes/indicators/search_field_theme.dart';
import '../../../widgets/custom_action_popup.dart';
import '../enquiry/policy_popup.dart';

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

class claimListState extends ConsumerState<claimList> {
  int currentPage = 1;
  int itemsPerPage = 10;
  late ApiService apiService;

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

  final TextEditingController _searchStaffController = TextEditingController();

  dynamic userId;
  dynamic roleId;
  dynamic managerId;

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

    apiService = ApiService();

    Future.microtask(() {
      final id = ref.read(managerIdProvider);
      managerId = ref.read(managerIdProvider);

      // roleId = ref.read(userRoleProvider);
      // roleId = ref.read(userRoleProvider);
      roleId = ref.read(userRoleProvider);
      userId = ref.read(userIdProvider);
      print("G47 => r : $roleId | mId: $id | uId: $userId ");
      if (userId != null) {
        getStaffList(managerId, userId, roleId);
      }
    });
  }

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

    try {
      final response = await apiService.fetchClaimList(managerId, userId, role);

      if (response['status'] == 'success') {
        final data = response['data'];
        print('F64 => clImlist => ${response['data']}');
        setState(() {
          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 filterData(String query) {
    print("FilterDAta - $query");
    setState(() {
      filteredData = getStaffData.where((item) {
        // final isActiveStatus = item['is_active'] == "1" ? "active" : "inactive";

        return (item['reg_no'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['insurer_short_name'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['policy_no'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['claim_type_value'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['claim_number'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (_formatDate(
              item['policy_end_date'] ?? '-',
            ).toLowerCase()).contains(query.toLowerCase());
      }).toList();
    });
  }

  String _formatDate(String rawDate) {
    try {
      final dateTime = DateTime.parse(rawDate);
      return DateFormat('dd-MM-yyyy').format(dateTime); // date only
    } 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('/staff/$id');
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.edit_sharp, color: Color(0xFF319718), size: 18),
            SizedBox(width: 10),
            Text('Edit'),
          ],
        ),
      ),
    ];
  }

  void refresh() {
    getStaffList(managerId, userId, roleId);
  }

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      title: "claims",
      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: [
            //         Tooltip(
            //           message: 'Back',
            //           child: IconButton(
            //             icon: const Icon(
            //               Icons.arrow_left_sharp,
            //               size: 25,
            //               color: 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(
            //           "Claims",
            //           style: GoogleFonts.poppins(
            //             fontSize: 12,
            //             fontWeight: FontWeight.w500,
            //           ),
            //         ),
            //       ],
            //     ),
            //   ),
            // ),
            //
            // SizedBox(height: 5),
            Expanded(
              child: Container(
                // color: Colors.green,
                // color: Colors.green.shade50,
                width: MediaQuery.of(context).size.width,

                padding: EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    Container(
                      // height: 40,
                      // color: Colors.pink,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            "Claims",
                            style: GoogleFonts.poppins(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          Spacer(),

                          ThemedSearchField(
                            hintText: 'Search',
                            backgroundColor: Color(0xFFFFFFFF),
                            txtHeight: 30,
                            // backgroundColor: Color(0xFFF6F8F8),
                            onChanged: filterData,
                            controller: _searchStaffController,
                            txtwidth: ResponsiveLayout.isMobile(context)
                                ? MediaQuery.of(context).size.width * 0.6
                                : MediaQuery.of(context).size.width * 0.15,
                          ),
                          SizedBox(width: 10),
                          ExportBtn(
                            sheetName: "Claims",
                            fileName: "claim_list",
                            data: filteredData,
                            txt: !ResponsiveLayout.isMobile(context)
                                ? true
                                : false,
                            displayHeaders: [
                              "S.No.",
                              "Vehicle.No.",
                              "Insurer",
                              "Policy No.",
                              "Policy Expiry Date",
                              "Claim Type",
                              "Claim No.",
                              "Status",
                            ],
                            keys: [
                              "sno", // handled internally as i + 1
                              "reg_no",
                              "insurer_short_name",
                              "policy_no",
                              "policy_end_date",
                              "claim_number",
                              "claim_type_value",
                              'claim_status_value',
                            ],
                          ),
                          SizedBox(width: 10),
                          InkWell(
                            onTap: () {
                              showDialog(
                                context: context,
                                builder: (ctx) => AddDialog(
                                  managerId: managerId,
                                  userId: userId,
                                  role: roleId,
                                  title: "Claims",
                                  // policyNumber: 'POC_n1',
                                  // policyNumber: selectedPolicyNumber,
                                  onSubmit: (value) {
                                    debugPrint("New Claims: $value");

                                    refresh();
                                    // enrollKey.currentState?.getEndrosmentList(selectedPolicyNumber);

                                    // Update claim list or call API
                                  },
                                ),
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.all(4.8),
                              decoration: BoxDecoration(
                                color: const Color(0xFF2E7D6E),
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Tooltip(
                                    message: 'Create Claims',
                                    child: Icon(
                                      Icons.add,
                                      color: Colors.white,
                                      size: 18,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),

                          // SizedBox(width: 10),
                          // GestureDetector(
                          //   onTap: () {
                          //     // print('Export');
                          //   },
                          //   child: Container(
                          //     padding: EdgeInsets.all(8.0),
                          //     decoration: BoxDecoration(
                          //       color: Color(0xFF425B5B),
                          //       borderRadius: BorderRadius.circular(8.0),
                          //     ),
                          //     child: Row(
                          //       mainAxisSize: MainAxisSize.min,
                          //       children: [
                          //         Icon(Icons.add, color: Colors.white),
                          //
                          //         if (!ResponsiveLayout.isMobile(context)) ...[
                          //           SizedBox(width: 10),
                          //
                          //           GestureDetector(
                          //             onTap: () {
                          //               // context.go(AppRoutes.agent / create);
                          //               context.go('/staff/create');
                          //             },
                          //             child: Text(
                          //               'Create New Staff',
                          //               style: GoogleFonts.inter(
                          //                 color: Colors.white,
                          //                 fontWeight: FontWeight.w600,
                          //                 fontSize: 14,
                          //               ),
                          //             ),
                          //           ),
                          //         ],
                          //       ],
                          //     ),
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                    if (!ResponsiveLayout.isMobile(context))
                      Container(
                        decoration: BoxDecoration(
                          // color: const Color(0xFFEDF6F5),
                          color: Color(0xFFF1F5F9),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        padding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                        child: Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Text('S.No.', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text('Vehicle.No.', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text('Insurer', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 3,
                              child: Text('Policy No.', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text(
                                'Policy Expiry Date',
                                style: _headerStyle,
                              ),
                            ),
                            Expanded(
                              flex: 3,
                              child: Text('Claim Type', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text('Claim No.', style: _headerStyle),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text('Status', style: _headerStyle),
                            ),
                          ],
                        ),
                      ),
                    Expanded(
                      child: Container(
                        color: Colors.white,
                        child: _buildDataTable(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 _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)
            ? Container(color: Colors.white, child: _buildDataRow(item, sno))
            : _buildDataCard(item, sno);
      },
    );
  }

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

  Widget _buildDataRow(Map<String, dynamic> item, sno) {
    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: 1, child: Text('$sno' ?? '-', style: _dataBold)),
          Expanded(
            flex: 2,
            child: Text(
              item['reg_no'] ?? '-', // fallback
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['insurer_short_name'] ?? '-', // fallback
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(item['policy_no'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 2,
            child: Text(
              // _formatDate(item['policy_end_date']) ?? '-',
              item['policy_end_date'] != null
                  ? _formatDate(item['policy_end_date'])
                  : '-',
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(
              item['claim_type_value'] ?? '-', // fallback
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['claim_number'] ?? '-', // fallback
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['claim_status_value'] ?? '-', // fallback
              style: _dataBold,
            ),
          ),

          // 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: [
              //reg no
              Text(
                item['reg_no'] != null ? _formatDate(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,
              //           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: [
                    //company
                    Text("Insurer", style: _cardheaderStyle),
                    Text(
                      item['policy_end_date'] != null
                          ? _formatDate(item['policy_end_date'])
                          : '-',
                      style: _cardBodyStyle,
                      maxLines: 3,
                      softWrap: true,
                    ),
                  ],
                ),
              ),
              SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    //status
                    Text("Claim Type", style: _cardheaderStyle),
                    Text(
                      item['claim_type_value'] ?? '-',
                      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: [
                    //date and time
                    Text("policy Number", style: _cardheaderStyle),
                    Text(item['policy_no'] ?? '-', style: _cardBodyStyle),
                  ],
                ),
              ),
              SizedBox(width: 5),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    //remarks
                    Text("Claim Number", style: _cardheaderStyle),
                    Text(
                      item['claim_number'] ?? '-',
                      style: _cardBodyStyle,
                      maxLines: 3,
                      softWrap: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 15),

          // Created On + Remarks
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    //date and time
                    Text("Status", style: _cardheaderStyle),
                    Text(
                      item['claim_status_value'] ?? '-',
                      style: _cardBodyStyle,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  static final _dataBold = GoogleFonts.inter(
    fontSize: 11.5,
    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,
  );
}
