import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:responsive_builder/responsive_builder.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../config/apiUrl.dart';
import '../../routes/custom_appBar.dart';
import '../../routes/custom_drawer.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
import '../../utils/pagination.dart';
import '../../widgets/custom_breadcrumb_navigation.dart';

class PolicyList extends StatefulWidget {
  @override
  _PolicyListState createState() => _PolicyListState();
}

class _PolicyListState extends State<PolicyList> {
  final ApiService apiService = ApiService();
  // late Future<List<dynamic>> futurePolicy;
  Future<List<dynamic>>? futurePolicy;

  late Map<String, dynamic> userSingleData;
  List<dynamic>? apiCountryData;
  String? selectedPolicyId;
  String? orgId;

  Color? layoutColor;
  Color? bodyColor;

  List allPolicy = [];
  List filteredPolicy = [];
  TextEditingController searchController = TextEditingController();

  int currentPage = 0;
  int itemsPerPage = 10;

  List<dynamic>? apiAllPolicy;

  @override
  void initState() {
    super.initState();
    _checkAuthAndLoadData();
    // futurePolicy = fetchPolicy();
    //
    // futurePolicy.then((object) {
    //   setState(() {
    //     allPolicy = object;
    //   });
    // });
    //
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   loadInitialData();
    //   fetchPolicy();
    // });

    // futurePlans = fetchPlans();
  }

  void _checkAuthAndLoadData() async {
    final String? token = await getToken(); // Your async function to get token

    if (token == null || token.isEmpty) {
      // Token doesn't exist → redirect to login
      context.go(
        "/",
      ); // or use: router.go("/") if you're using `GoRouter` directly
      return;
    }
    if (!mounted) return;
    try {
      final roleUser = await getRoleUser();

      if (roleUser != null &&
          (roleUser == 'Org Admin' || roleUser == 'Travel Admin')) {
        futurePolicy = fetchPolicy();

        futurePolicy?.then((object) {
          setState(() {
            allPolicy = object;
          });
        });

        loadInitialData();
        fetchPolicy();
      } else {
        apiService.logout(context);
      }
    } catch (e) {
      print("group : $e");
    }
  }

  void loadInitialData() async {
    String? layoutString = await getLayoutColor();
    String? bodyStringColor = await getBodyColor();

    setState(() {
      layoutColor =
          layoutString != null
              ? Color(int.parse(layoutString))
              : Colors.redAccent;

      bodyColor =
          bodyStringColor != null
              ? Color(int.parse(bodyStringColor))
              : Colors.white;
    });
  }

  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('auth_token');
  }

  Future<List<dynamic>> fetchPolicy() async {
    final data = await apiService.fetchAllPolicy(context);
    return data; // Returning raw JSON list
  }

  // Refresh user list after update
  void refreshPolicyList() {
    setState(() {
      futurePolicy = fetchPolicy(); // Re-fetch users after status update

      futurePolicy?.then((object) {
        setState(() {
          allPolicy = object;
          filteredPolicy = object;
          searchController.text = "";
        });
      });
      // Wait for futurePlans to be fetched and update allPlans
    });
  }

  void filterPolicy(String query) {
    print("all before filtering: $query");
    final lowerQuery = query.toLowerCase();
    setState(() {
      filteredPolicy =
          allPolicy.where((object) {
            final isActiveStatus =
                object['is_active'] == "1" ? "active" : "inactive";
            return (object['policy_id']?.toLowerCase().contains(lowerQuery) ??
                    false) ||
                (object['name']?.toLowerCase().contains(lowerQuery) ?? false) ||
                (object['policy_type']?.toLowerCase().contains(lowerQuery) ??
                    false) ||
                (isActiveStatus.contains(lowerQuery));
          }).toList();
      currentPage = 0;
    });
    print("filteredPolicy: $filteredPolicy");
  }

  void handleActiveStatus(
    Map<String, dynamic> policyData,
    String policyId,
    String currentStatus,
  ) async {
    print("Toggling user status - $policyId (Current: $currentStatus)");

    final String apiUrlData =
        '$apiUrl/api/policy/createOrUpdate'; // API for updating user
    final String? token = await getToken();

    if (token == null) {
      print("Error: Token not found");
      return;
    }

    // Toggle status: If active ("1"), set to inactive ("0"); otherwise, activate ("1")
    String newStatus = (currentStatus == "1") ? "0" : "1";

    print("STatus 1 - $newStatus");

    final int? selectedPolicyId;

    if (policyId.isNotEmpty) {
      selectedPolicyId = int.tryParse(policyId);
      policyData['policy_id'] = selectedPolicyId; // Add only if updating
      policyData['is_active'] = newStatus; // Add only if updating
    }

    try {
      final response = await http.post(
        Uri.parse(apiUrlData),
        headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
          'app-signature': 'ts-traveltool-2025-signature-123456',
        },
        body: jsonEncode(policyData), // Convert map to JSON
      );

      if (response.statusCode == 200) {
        print("policyData submitted successfully!");
        print("Response: ${response.body}");
        loadAllGroups();
      } else if (response.statusCode == 403) {
        print("403-FORB");
        await apiService.logout(context);
        return null;
        // throw Exception('Failed to load users');
      } else {
        print("Failed to submit policyData. Status: ${response.statusCode}");
        print("Error: ${response.body}");
      }
    } catch (e) {
      print(" Error submitting policyData: $e");
    }
  }

  void deletePolicy(Map<String, dynamic> policydata, policyId, status) {
    print("policyId : $policyId");
    print("policystatus: $status");
    print("policysData: $policydata");

    handleActiveStatus(policydata, policyId.toString(), status.toString());
  }

  Future<void> refreshData() async {
    loadAllGroups();
  }

  Future<void> loadAllGroups() async {
    try {
      final result = await apiService.fetchAllPolicy(context);
      setState(() {
        allPolicy = result;
        filteredPolicy = result;
        searchController.text = "";
      });
      print("Fetched services: $allPolicy");
    } catch (e) {
      print('Error fetching role list: $e');
    }
  }

  // Future<void> loadAllGroups_old() async {
  //   try {
  //     final result = await apiService.fetchAllPolicy();
  //
  //     // Sort by policy_id descending (latest first)
  //     result.sort((a, b) {
  //       int idA = int.tryParse(a['policy_id'].toString()) ?? 0;
  //       int idB = int.tryParse(b['policy_id'].toString()) ?? 0;
  //       return idB.compareTo(idA); // latest first
  //     });
  //
  //     setState(() {
  //       futurePolicy = result as Future<List>;
  //     });
  //     print("Fetched services: $futurePolicy");
  //     refreshPolicyList();
  //   } catch (e) {
  //     print('Error fetching role list: $e');
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInfo) {
        bool isDesktop =
            sizingInfo.deviceScreenType == DeviceScreenType.desktop;

        return Scaffold(
          backgroundColor: Color(0xFFf5f5f5),
          // appBar: isDesktop ? null : const CustomAppBar(title: 'User Management'),
          // drawer: isDesktop ? null : CustomDrawer(isDesktop: false),
          appBar: CustomAppBar(isDesktop: isDesktop),
          drawer: CustomDrawer(isDesktop: false),
          body: Padding(
            padding:
                isDesktop
                    ? EdgeInsets.symmetric(
                      horizontal:
                          MediaQuery.of(context).size.width *
                          0.1, // 30% of screen width as horizontal padding
                      vertical:
                          MediaQuery.of(context).size.height *
                          0, // 5% of screen height as vertical padding
                    )
                    : EdgeInsets.all(0),
            child: Row(
              children: [
                // if (isDesktop) CustomDrawer(isDesktop: true),
                // const Expanded(child: Center(child: Text("User Page Content"))),
                Expanded(child: buildGroupList(isDesktop)),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget buildGroupList(bool isDesktop) {
    return Container(
      margin: isDesktop ? const EdgeInsets.only(top: 10.0, bottom: 10.0) : null,
      padding: const EdgeInsets.all(1),
      decoration: BoxDecoration(
        color: isDesktop ? Colors.white : Color(0xFFFCFCFC),
      ),
      // decoration: BoxDecoration(
      //     // color: Colors.amber,
      //     // color: bodyColor,
      //     color: Color(0xFFE1F5FE),
      //     border: Border.all(
      //         color: Colors.white,
      //         // color: Color(0xFFF7F7FB),
      //         width: 3.5)),
      child: buildUserTable(isDesktop),
    );
  }

  Widget buildUserTable(bool isDesktop) {
    return Container(
      // margin: isDesktop
      //     ? EdgeInsets.all(10.0)
      //     : EdgeInsets.only(left: 20.0, bottom: 20.0, top: 10.0, right: 20.0),
      // padding: const EdgeInsets.all(10),
      height:
          isDesktop
              ? MediaQuery.of(context).size.height * 0.98
              : MediaQuery.of(context).size.height,

      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Divider(
              //   thickness: 0.2, // how "thick" the line is
              //   color: Colors.grey, // optional
              // ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Container(
                        child: BreadcrumbNavigation(
                          isDesktop: isDesktop,
                          breadcrumbItems: [
                            BreadcrumbItem(
                              title: 'Org Settings',
                              tooltip: 'Go To Organization Settings',
                              onTap: (context) {
                                context.go("/OrganizationSettings");
                              },
                            ),
                            BreadcrumbItem(title: 'Policy'),
                          ],
                        ),
                      ),
                      // Text(
                      //   'Policy',
                      //   style: GoogleFonts.poppins(
                      //     fontSize: isDesktop ? 16 : 14,
                      //     fontWeight: FontWeight.w600,
                      //     color: Colors.black,
                      //   ),
                      // ),
                    ],
                  ),
                  if (isDesktop)
                    SizedBox(width: MediaQuery.of(context).size.width * 0.145),

                  // SizedBox(width: MediaQuery.of(context).size.width * 0.28),
                  if (isDesktop)
                    Container(
                      width: MediaQuery.of(context).size.width * 0.2,
                      height: 40,
                      child: TextField(
                        controller: searchController,
                        onChanged: filterPolicy,
                        decoration: InputDecoration(
                          hintText: "Search ...",

                          hintStyle: TextStyle(
                            fontSize: 12,
                            color: Color(0xFF9E9DBD),
                          ),
                          prefixIcon: Icon(
                            Icons.search,
                            color: Color(0xFF9E9DBD),
                            size: 18,
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide(
                              color: Colors.grey.shade200,
                              width: 0.5,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide(
                              color: Colors.grey.shade300,
                              width: 1,
                            ),
                          ),
                        ),
                        style: GoogleFonts.poppins(fontSize: 12),
                      ),
                    ),
                  // SizedBox(width: 16),
                  Spacer(),

                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFF114D8B),
                      foregroundColor: Colors.white,
                      disabledBackgroundColor: Color(0xFF114D8B),
                      disabledForegroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                        side: BorderSide(color: Color(0xFF114D8B), width: 2),
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 12,
                      ),
                    ),
                    onPressed: () async {
                      List? policyData = await futurePolicy;

                      // Print the resolved value
                      print("CREATELIAS - $policyData");
                      context.go('/Policy');
                    },
                    child: Row(
                      mainAxisSize:
                          MainAxisSize.min, // Ensures content fits nicely
                      children: [
                        Text(
                          "Add Policy",
                          style: GoogleFonts.poppins(
                            fontSize: isDesktop ? 13 : 11,
                          ),
                        ),
                        SizedBox(width: 8), // spacing between icon and text
                        Icon(
                          Icons.add_circle_outline_rounded,
                          size: 15,
                          color: Colors.white,
                        ),
                      ],
                    ),
                  ),
                ],
              ),

              if (!isDesktop) SizedBox(height: 5),
              isDesktop
                  ? SizedBox.shrink()
                  : Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        width: MediaQuery.of(context).size.width * 0.8,
                        height: 35,
                        child: TextField(
                          controller: searchController,
                          onChanged: filterPolicy,
                          decoration: InputDecoration(
                            hintText: "Search ...",
                            hintStyle: TextStyle(
                              fontSize: 12,
                              color: Color(0xFF9E9DBD),
                            ),
                            prefixIcon: Icon(
                              Icons.search,
                              color: Color(0xFF9E9DBD),
                              size: 18,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide(
                                color: Colors.grey.shade200,
                                width: 0.5,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide(
                                color: Colors.grey.shade300,
                                width: 1,
                              ),
                            ),
                          ),
                          style: GoogleFonts.poppins(fontSize: 12),
                        ),
                      ),
                      // SizedBox(width: 16),
                    ],
                  ),
              const SizedBox(height: 10),
              FutureBuilder<List<dynamic>>(
                future: futurePolicy,
                builder: (context, snapshot) {
                  final adjHgt = MediaQuery.of(context).size.height;
                  if (futurePolicy == null) {
                    return const CircularProgressIndicator();
                  }

                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Center(child: CircularProgressIndicator());
                  } else if (snapshot.hasError ||
                      !snapshot.hasData ||
                      snapshot.data!.isEmpty) {
                    return Center(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(height: adjHgt / 4),
                            Text(
                              "No Data Found",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.poppins(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                color: Colors.grey,
                              ),
                            ),
                            const SizedBox(height: 20),
                            // Text(
                            //   "Please Create Policy",
                            //   textAlign: TextAlign.center,
                            //   style: GoogleFonts.poppins(
                            //     fontSize: 16,
                            //     color: Colors.grey,
                            //   ),
                            // ),
                            // const SizedBox(height: 20),
                          ],
                        ),
                      ),
                    );
                  }

                  List<dynamic> policyData =
                      filteredPolicy.isNotEmpty ? filteredPolicy : allPolicy;

                  policyData.sort((a, b) {
                    DateTime dateA = DateTime.parse(a['created_on']);
                    DateTime dateB = DateTime.parse(b['created_on']);

                    return dateB.compareTo(dateA); // Descending: newest first
                  });

                  List paginatedUser =
                      policyData
                          .skip(currentPage * itemsPerPage)
                          .take(itemsPerPage)
                          .toList();

                  Widget table = LayoutBuilder(
                    builder: (context, constraints) {
                      double minWidth = isDesktop ? constraints.maxWidth : 1300;

                      return ConstrainedBox(
                        constraints: BoxConstraints(minWidth: minWidth),
                        child: DataTable(
                          dividerThickness: 0.5,
                          columnSpacing: isDesktop ? 24.0 : 16.0,
                          border: TableBorder(
                            horizontalInside: BorderSide(
                              width: 0.5,
                              color: Colors.grey.shade200,
                            ),
                          ),
                          columns: [
                            DataColumn(
                              label: Text(
                                'Policy Name',
                                style: GoogleFonts.poppins(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                            DataColumn(
                              label: Text(
                                'Policy Type',
                                style: GoogleFonts.poppins(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                            DataColumn(
                              label: Text(
                                'Status',
                                style: GoogleFonts.poppins(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                            DataColumn(
                              label: Text(
                                'Actions',
                                style: GoogleFonts.poppins(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ],
                          rows:
                              paginatedUser.map((policy) {
                                String policyId =
                                    policy['policy_id']
                                        .toString(); // Get policy ID
                                bool isSelected = selectedPolicyId == policyId;

                                return DataRow(
                                  cells: [
                                    DataCell(
                                      Text(
                                        "${policy['name'] ?? ''}",
                                        style: TextStyle(
                                          fontSize: 13,
                                          fontFamily: "Inter",
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      Text(
                                        policy['domestic'] == "1"
                                            ? "Domestic"
                                            : "International",
                                        style: TextStyle(
                                          fontSize: 13,
                                          fontFamily: "Inter",
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      Text(
                                        policy['is_active'] == "1"
                                            ? "Active"
                                            : "Inactive",
                                        style: TextStyle(
                                          color:
                                              policy['is_active'] == "1"
                                                  ? Colors.green
                                                  : Colors.grey,
                                          fontFamily: "Inter",
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: [
                                          GestureDetector(
                                            onTap: () async {
                                              final rawId = policy['policy_id'];
                                              final intPolicyId =
                                                  rawId is int
                                                      ? rawId
                                                      : int.tryParse(
                                                            rawId.toString(),
                                                          ) ??
                                                          0;

                                              Map<String, dynamic> policyData =
                                                  await apiService
                                                      .getSinglePolicy(
                                                        intPolicyId,
                                                        context,
                                                      );

                                              print("PolicyDATa: $policyData");

                                              context.go(
                                                "/Policy",
                                                extra: policyData,
                                              );
                                            },
                                            child: Tooltip(
                                              message: 'Edit Policy Details',
                                              child: Image.asset(
                                                'assets/images/IconsImg/edit.png',
                                                width: 20,
                                                height: 15,
                                              ),
                                            ),
                                          ),
                                          SizedBox(width: 5),
                                          GestureDetector(
                                            onTap: () {
                                              final idStr = policy['policy_id'];
                                              final id = int.tryParse(
                                                idStr.toString(),
                                              );

                                              if (id == null) {
                                                print("group_id is null");
                                                return;
                                              }
                                              final status =
                                                  policy['is_active'];

                                              deletePolicy(policy, id, status);
                                            },
                                            child: Tooltip(
                                              message: 'Delete Policy Details',
                                              child: Image.asset(
                                                'assets/images/IconsImg/delete.png',
                                                width: 20,
                                                height: 15,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                );
                              }).toList(),
                        ),
                      );
                    },
                  );
                  Widget buildMobileCardView(List<dynamic> paginatedUser) {
                    return ListView.builder(
                      itemCount: paginatedUser.length,
                      itemBuilder: (context, index) {
                        final object = paginatedUser[index];

                        return Card(
                          color: Colors.white,
                          margin: EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 6,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          elevation: 3,
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // Row 1: Policy Name and Actions
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Expanded(
                                      child: RichText(
                                        text: TextSpan(
                                          style: GoogleFonts.poppins(
                                            fontSize: 13,
                                            color: Colors.black,
                                          ),
                                          children: [
                                            TextSpan(
                                              text: "Policy Name: ",
                                              style: GoogleFonts.poppins(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600,
                                              ),
                                            ),
                                            TextSpan(
                                              text:
                                                  "${object['name'] ?? 'N/A'}",
                                              style: TextStyle(
                                                fontSize: 13,
                                                fontFamily: "Inter",
                                                fontWeight: FontWeight.normal,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        GestureDetector(
                                          onTap: () async {
                                            final rawId = object['policy_id'];
                                            final intPolicyId =
                                                rawId is int
                                                    ? rawId
                                                    : int.tryParse(
                                                          rawId.toString(),
                                                        ) ??
                                                        0;

                                            Map<String, dynamic> policyData =
                                                await apiService
                                                    .getSinglePolicy(
                                                      intPolicyId,
                                                      context,
                                                    );

                                            print("PolicyDATa: $policyData");

                                            context.go(
                                              "/Policy",
                                              extra: policyData,
                                            );
                                          },
                                          child: Tooltip(
                                            message: 'Edit Policy Details',
                                            child: Image.asset(
                                              'assets/images/IconsImg/edit.png',
                                              width: 20,
                                              height: 15,
                                            ),
                                          ),
                                        ),
                                        SizedBox(width: 5),
                                        GestureDetector(
                                          onTap: () {
                                            final idStr = object['policy_id'];
                                            final id = int.tryParse(
                                              idStr.toString(),
                                            );

                                            if (id == null) {
                                              print("policy_id is null");
                                              return;
                                            }
                                            final status = object['is_active'];

                                            deletePolicy(object, id, status);
                                          },
                                          child: Tooltip(
                                            message: 'Delete Policy Details',
                                            child: Image.asset(
                                              'assets/images/IconsImg/delete.png',
                                              width: 20,
                                              height: 15,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),

                                SizedBox(height: 8), // Spacing
                                // Row 2: Policy Type
                                RichText(
                                  text: TextSpan(
                                    style: GoogleFonts.poppins(
                                      fontSize: 13,
                                      color: Colors.black,
                                    ),
                                    children: [
                                      TextSpan(
                                        text: "Policy Type: ",
                                        style: GoogleFonts.poppins(
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      TextSpan(
                                        text:
                                            object['domestic'] == "1"
                                                ? "Domestic"
                                                : "International",
                                        style: TextStyle(
                                          fontSize: 13,
                                          fontFamily: "Inter",
                                          fontWeight: FontWeight.normal,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    );
                  }

                  Widget buildMobileCardView2(List<dynamic> paginatedUser) {
                    return ListView.builder(
                      itemCount: paginatedUser.length,
                      itemBuilder: (context, index) {
                        final object = paginatedUser[index];
                        return Card(
                          color: Colors.white,
                          margin: EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 6,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          elevation: 3,
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Column(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: Text(
                                        "Policy Type",
                                        style: GoogleFonts.poppins(
                                          fontSize: 11.5,
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ),
                                    // Expanded(flex: 1, child: Text("${policy['created_by']}")),
                                  ],
                                ),
                                SizedBox(height: 4),
                                Column(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: Text(
                                        "${object['name']}",
                                        style: GoogleFonts.poppins(
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: Text(
                                        object['domestic'] == "1"
                                            ? "Domestic"
                                            : "International",
                                        style: GoogleFonts.poppins(
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                    // Expanded(flex: 1, child: Text("${policy['created_by']}")),
                                  ],
                                ),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    GestureDetector(
                                      onTap: () async {
                                        final rawId = object['policy_id'];
                                        final intPolicyId =
                                            rawId is int
                                                ? rawId
                                                : int.tryParse(
                                                      rawId.toString(),
                                                    ) ??
                                                    0;

                                        Map<String, dynamic> policyData =
                                            await apiService.getSinglePolicy(
                                              intPolicyId,
                                              context,
                                            );

                                        print("PolicyDATa: $policyData");

                                        context.go(
                                          "/Policy",
                                          extra: policyData,
                                        );
                                      },
                                      child: Tooltip(
                                        message: 'Edit Policy Details',
                                        child: Image.asset(
                                          'assets/images/IconsImg/edit.png',
                                          width: 20,
                                          height: 15,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 5),
                                    GestureDetector(
                                      onTap: () {
                                        final idStr = object['policy_id'];
                                        final id = int.tryParse(
                                          idStr.toString(),
                                        );

                                        if (id == null) {
                                          print("group_id is null");
                                          return;
                                        }
                                        final status = object['is_active'];

                                        deletePolicy(object, id, status);
                                      },
                                      child: Tooltip(
                                        message: 'Delete Policy Details',
                                        child: Image.asset(
                                          'assets/images/IconsImg/delete.png',
                                          width: 20,
                                          height: 15,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    );
                  }

                  return Expanded(
                    child: Column(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child:
                              isDesktop
                                  ? (searchController.text.isNotEmpty &&
                                          filteredPolicy.isEmpty
                                      ? Center(
                                        child: Text(
                                          "No Matches Found",
                                          style: GoogleFonts.poppins(
                                            fontSize: 14,
                                            color: Colors.grey,
                                          ),
                                        ),
                                      )
                                      : SingleChildScrollView(
                                        scrollDirection: Axis.vertical,
                                        child: table,
                                      ))
                                  : (searchController.text.isNotEmpty &&
                                          filteredPolicy.isEmpty
                                      ? Center(
                                        child: Text(
                                          "No Matches Found",
                                          style: GoogleFonts.poppins(
                                            fontSize: 14,
                                            color: Colors.grey,
                                          ),
                                        ),
                                      )
                                      : buildMobileCardView(paginatedUser)),
                        ),
                        PaginationControls(
                          currentPage: currentPage,
                          itemsPerPage: itemsPerPage,
                          totalItems: policyData.length,
                          activeColor: layoutColor, // your theme color
                          onPageChanged: (page) {
                            setState(() {
                              currentPage = page;
                            });
                          },
                          onItemsPerPageChanged: (items) {
                            setState(() {
                              itemsPerPage = items;
                              currentPage = 0;
                            });
                          },
                        ),
                      ],
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
