import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/GlobalComponents/button_global.dart';
import 'package:mobile_pos/Provider/customer_provider.dart';
import 'package:mobile_pos/Screens/Customers/add_customer.dart';
import 'package:mobile_pos/Screens/Customers/customer_details.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/constant.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../Home/home.dart';
import 'Model/customer_model.dart';

// Pagination Provider for Customer List
final customerListPaginationProvider = StateNotifierProvider.family<CustomerListPaginationNotifier,
    CustomerListPaginationState, String>((ref, type) {
  return CustomerListPaginationNotifier(type: type);
});

class CustomerListPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<CustomerModel> displayedCustomers;
  final String searchQuery;
  final String type;

  CustomerListPaginationState({
    this.currentPage = 1,
    this.itemsPerPage = 10,
    this.isLoading = false,
    this.hasMore = true,
    List<CustomerModel>? displayedCustomers,
    this.searchQuery = '',
    required this.type,
  }) : displayedCustomers = displayedCustomers ?? [];

  CustomerListPaginationState copyWith({
    int? currentPage,
    int? itemsPerPage,
    bool? isLoading,
    bool? hasMore,
    List<CustomerModel>? displayedCustomers,
    String? searchQuery,
    String? type,
  }) {
    return CustomerListPaginationState(
      currentPage: currentPage ?? this.currentPage,
      itemsPerPage: itemsPerPage ?? this.itemsPerPage,
      isLoading: isLoading ?? this.isLoading,
      hasMore: hasMore ?? this.hasMore,
      displayedCustomers: displayedCustomers ?? this.displayedCustomers,
      searchQuery: searchQuery ?? this.searchQuery,
      type: type ?? this.type,
    );
  }
}

class CustomerListPaginationNotifier extends StateNotifier<CustomerListPaginationState> {
  CustomerListPaginationNotifier({required String type})
      : super(CustomerListPaginationState(type: type));

  void resetPagination({String? searchQuery}) {
    state = state.copyWith(
      currentPage: 1,
      displayedCustomers: [],
      hasMore: true,
      searchQuery: searchQuery ?? state.searchQuery,
    );
  }

  void updateSearchQuery(String query) {
    state = state.copyWith(
      searchQuery: query,
      currentPage: 1,
      displayedCustomers: [],
      hasMore: true,
    );
  }

  void loadMoreCustomers(List<CustomerModel> allCustomers) {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    // Filter customers based on type and search query
    final filteredCustomers = _filterCustomers(allCustomers);

    final totalItems = filteredCustomers.length;
    final startIndex = (state.currentPage - 1) * state.itemsPerPage;
    final endIndex = startIndex + state.itemsPerPage;

    // Check if we have more items to load
    final hasMoreItems = endIndex < totalItems;

    // Get the next batch of customers
    final nextBatch = endIndex <= totalItems
        ? filteredCustomers.sublist(startIndex, endIndex)
        : filteredCustomers.sublist(startIndex);

    // Update state
    final newDisplayedCustomers = [...state.displayedCustomers, ...nextBatch];

    state = state.copyWith(
      currentPage: state.currentPage + 1,
      isLoading: false,
      hasMore: hasMoreItems,
      displayedCustomers: newDisplayedCustomers,
    );
  }

  List<CustomerModel> _filterCustomers(List<CustomerModel> customers) {
    return customers.where((customer) {
      // Filter by type
      if (state.type != 'All' && customer.type != state.type) {
        return false;
      }

      // Apply search filter if query is provided
      if (state.searchQuery.isNotEmpty) {
        final matchesName =
            customer.customerName.toLowerCase().contains(state.searchQuery.toLowerCase());
        final matchesPhone = customer.phoneNumber.contains(state.searchQuery);
        return matchesName || matchesPhone;
      }

      return true;
    }).toList();
  }
}

class CustomerList extends StatefulWidget {
  const CustomerList({super.key});

  @override
  State<CustomerList> createState() => _CustomerListState();
}

class _CustomerListState extends State<CustomerList> with SingleTickerProviderStateMixin {
  late Color color;
  List<String> type = ['All', 'Retailer', 'Supplier', 'Wholesaler', 'Dealer'];

  late String typeName = type.first;
  int typeIndex = 0;
  String? partyName;
  TabController? tabController;
  final TextEditingController _searchController = TextEditingController();
  final Map<String, ScrollController> _scrollControllers = {};

  @override
  void initState() {
    tabController = TabController(length: 5, vsync: this);

    // Initialize scroll controllers for each tab
    for (final tabType in type) {
      _scrollControllers[tabType] = ScrollController();
    }

    // Add scroll listeners
    for (final controller in _scrollControllers.values) {
      controller.addListener(_scrollListener);
    }

    // Search debounce
    _searchController.addListener(() {
      if (_searchController.text != partyName) {
        _debounceSearch();
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    tabController?.dispose();
    _searchController.dispose();
    for (final controller in _scrollControllers.values) {
      controller.dispose();
    }
    super.dispose();
  }

  void _scrollListener() {
    final currentType = type[tabController!.index];
    final controller = _scrollControllers[currentType];

    if (controller != null && controller.position.pixels == controller.position.maxScrollExtent) {
      _loadMoreData(currentType);
    }
  }

  void _loadMoreData(String type) {
    final ref = ProviderScope.containerOf(context);
    final providerData = ref.read(customerProvider);

    providerData.whenData((customers) {
      ref.read(customerListPaginationProvider(type).notifier).loadMoreCustomers(customers);
    });
  }

  void _resetAndLoadData(String type) {
    final ref = ProviderScope.containerOf(context);
    ref
        .read(customerListPaginationProvider(type).notifier)
        .resetPagination(searchQuery: _searchController.text);
    _loadMoreData(type);
  }

  void _debounceSearch() {
    Future.delayed(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          partyName = _searchController.text;
        });

        // Reset pagination for all tabs when search changes
        final ref = ProviderScope.containerOf(context);
        for (final tabType in type) {
          ref
              .read(customerListPaginationProvider(tabType).notifier)
              .updateSearchQuery(_searchController.text);
          _resetAndLoadData(tabType);
        }
      }
    });
  }

  Widget _buildCustomerListItem(CustomerModel customer, Color color) {
    return Column(
      children: [
        GestureDetector(
          onTap: () {
            CustomerDetails(customerModel: customer).launch(context);
          },
          child: ListTile(
            horizontalTitleGap: 10,
            contentPadding: EdgeInsets.zero,
            leading: SizedBox(
              height: 50.0,
              width: 50.0,
              child: CircleAvatar(
                foregroundColor: Colors.blue,
                backgroundColor: kMainColor,
                radius: 70.0,
                child: ClipOval(
                  child: Text(
                    customer.customerName.isNotEmpty ? customer.customerName.substring(0, 1) : '',
                    style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Text(
                    customer.customerName.isNotEmpty
                        ? customer.customerName
                        : customer.phoneNumber,
                    style: kTextStyle.copyWith(color: kTitleColor),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 10),
                Visibility(
                  visible: customer.dueAmount != '' && customer.dueAmount != '0',
                  child: Text(
                    '$currency ${myFormat.format((customer.dueAmount ?? 0).toString().toDouble())}',
                    style: GoogleFonts.poppins(
                      color: Colors.black,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ],
            ),
            subtitle: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  customer.type,
                  style: kTextStyle.copyWith(color: color, fontSize: 15.0),
                ),
                Visibility(
                  visible: customer.dueAmount != '' && customer.dueAmount != '0',
                  child: Text(
                    lang.S.of(context).due,
                    style: kTextStyle.copyWith(color: const Color(0xFFff5f00), fontSize: 15),
                  ),
                ),
              ],
            ),
            trailing: const Icon(
              Icons.arrow_forward_ios,
              color: kGreyTextColor,
            ),
          ),
        ),
        Divider(
          height: 1,
          thickness: 1.0,
          color: kBorderColor.withValues(alpha: 0.3),
        )
      ],
    );
  }

  Widget _buildTabContent(String tabType) {
    return Consumer(
      builder: (context, ref, __) {
        final providerData = ref.watch(customerProvider);
        final paginationState = ref.watch(customerListPaginationProvider(tabType));

        return providerData.when(
          data: (allCustomers) {
            // Initial load of data
            if (paginationState.displayedCustomers.isEmpty && !paginationState.isLoading) {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                _resetAndLoadData(tabType);
              });
            }

            final filteredCustomers = allCustomers.where((customer) {
              if (tabType != 'All' && customer.type != tabType) return false;
              if (_searchController.text.isNotEmpty) {
                return customer.customerName
                        .toUpperCase()
                        .contains(_searchController.text.toUpperCase()) ||
                    customer.phoneNumber.contains(_searchController.text);
              }
              return true;
            }).toList();

            return paginationState.displayedCustomers.isNotEmpty || paginationState.isLoading
                ? SingleChildScrollView(
                    controller: _scrollControllers[tabType],
                    child: Column(
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: paginationState.displayedCustomers.length +
                              (paginationState.hasMore ? 1 : 0),
                          itemBuilder: (_, index) {
                            // Loading indicator at the end
                            if (index == paginationState.displayedCustomers.length) {
                              return paginationState.hasMore
                                  ? const Padding(
                                      padding: EdgeInsets.all(16.0),
                                      child: Center(
                                        child: CircularProgressIndicator(),
                                      ),
                                    )
                                  : filteredCustomers.isNotEmpty
                                      ? Padding(
                                          padding: const EdgeInsets.all(16.0),
                                          child: Center(
                                            child: Text(
                                              lang.S.of(context).noCustomerFound,
                                              style: const TextStyle(color: Colors.grey),
                                            ),
                                          ),
                                        )
                                      : const SizedBox.shrink();
                            }

                            final customer = paginationState.displayedCustomers[index];

                            // Set color based on customer type
                            if (customer.type == 'Retailer') {
                              color = const Color(0xFF56da87);
                            } else if (customer.type == 'Wholesaler') {
                              color = const Color(0xFF25a9e0);
                            } else if (customer.type == 'Dealer') {
                              color = const Color(0xFFff5f00);
                            } else if (customer.type == 'Supplier') {
                              color = const Color(0xFFA569BD);
                            } else {
                              color = Colors.black26;
                            }

                            return _buildCustomerListItem(customer, color);
                          },
                        ),
                      ],
                    ),
                  )
                : _searchController.text.isNotEmpty
                    ? Center(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 60),
                          child: Text(
                            lang.S.of(context).noCustomerFound,
                            style: const TextStyle(color: Colors.grey, fontSize: 16),
                          ),
                        ),
                      )
                    : const Center(
                        child: Padding(
                          padding: EdgeInsets.only(top: 60),
                          child: EmptyScreenWidget(),
                        ),
                      );
          },
          error: (e, stack) {
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Text(
                  'Error loading customers: $e',
                  style: const TextStyle(color: Colors.red),
                  textAlign: TextAlign.center,
                ),
              ),
            );
          },
          loading: () {
            return const Center(child: CircularProgressIndicator());
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 0,
      length: type.length,
      child: Scaffold(
        backgroundColor: kMainColor,
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          backgroundColor: kMainColor,
          title: Text(
            lang.S.of(context).partiesList,
            style: GoogleFonts.poppins(
              color: Colors.white,
            ),
          ),
          leading: const Icon(
            Icons.arrow_back,
            color: Colors.white,
          ).onTap(() async {
            await Future.delayed(const Duration(microseconds: 100))
                .then((value) => const Home().launch(context));
          }),
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.white),
          elevation: 0.0,
        ),
        body: WillPopScope(
          onWillPop: () async {
            await Future.delayed(const Duration(microseconds: 100)).then((value) {
              if (mounted) {
                const Home().launch(context);
                return true;
              } else {
                return false;
              }
            });
            return false;
          },
          child: Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(30), topLeft: Radius.circular(30))),
            child: Column(
              children: [
                const SizedBox(height: 10.0),
                TabBar(
                  controller: tabController,
                  tabAlignment: TabAlignment.start,
                  indicatorSize: TabBarIndicatorSize.tab,
                  labelColor: kMainColor,
                  unselectedLabelColor: kGreyTextColor,
                  onTap: (val) {
                    setState(() {
                      typeName = type[tabController!.index];
                      typeIndex = tabController!.index;
                    });
                  },
                  padding: EdgeInsets.zero,
                  isScrollable: true,
                  tabs: List.generate(
                    type.length,
                    (index) => Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        type[index],
                        style: const TextStyle(fontSize: 18.0),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 10.0),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 0.0),
                  child: AppTextField(
                    controller: _searchController,
                    textFieldType: TextFieldType.NAME,
                    onChanged: (value) {
                      setState(() {
                        partyName = value;
                      });
                    },
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        labelText: lang.S.of(context).partyName,
                        hintText: lang.S.of(context).enterPartyName,
                        border: const OutlineInputBorder(),
                        prefixIcon: const Icon(Icons.search)),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
                    child: TabBarView(
                      controller: tabController,
                      children: type.map((tabType) => _buildTabContent(tabType)).toList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        bottomNavigationBar: Container(
          color: Colors.white,
          child: ButtonGlobal(
            iconWidget: Icons.add,
            buttontext: lang.S.of(context).addCustomer,
            iconColor: Colors.white,
            buttonDecoration: kButtonDecoration.copyWith(
                color: kMainColor, borderRadius: const BorderRadius.all(Radius.circular(30))),
            onPressed: () async {
              if (await checkUserRolePermission(type: "customer-list-create")) {
                const AddCustomer(
                  fromWhere: 'customer_list',
                ).launch(context);
              }
            },
          ),
        ),
      ),
    );
  }
}

// class CustomerList extends StatefulWidget {
//   const CustomerList({super.key});
//
//   @override
//   State<CustomerList> createState() => _CustomerListState();
// }
//
// class _CustomerListState extends State<CustomerList> with SingleTickerProviderStateMixin {
//   late Color color;
//   List<String> type = [
//     // lang.S.current.all,
//     'All',
//     // lang.S.current.retailer,
//     'Retailer',
//     // lang.S.current.supplier,
//     'Supplier',
//     // lang.S.current.wholesaler,
//     'Wholesaler',
//     // lang.S.current.dealer,
//     'Dealer'
//   ];
//
//   late String typeName = type.first;
//   int typeIndex = 0;
//   String? partyName;
//   TabController? tabController;
//
//   @override
//   void initState() {
//     tabController = TabController(length: 5, vsync: this);
//     super.initState();
//   }
//
//   // String _formatAmount(String? amountString) {
//   //   final amount = int.tryParse(amountString ?? '0') ?? 0;
//   //   final myFormat = NumberFormat.decimalPattern('en_US');
//   //   return myFormat.format(amount);
//   // }
//
//   @override
//   Widget build(BuildContext context) {
//     return DefaultTabController(
//       initialIndex: 0,
//       length: type.length,
//       child: Scaffold(
//         backgroundColor: kMainColor,
//         resizeToAvoidBottomInset: true,
//         appBar: AppBar(
//           backgroundColor: kMainColor,
//           title: Text(
//             lang.S.of(context).partiesList,
//             style: GoogleFonts.poppins(
//               color: Colors.white,
//             ),
//           ),
//           leading: const Icon(
//             Icons.arrow_back,
//             color: Colors.white,
//           ).onTap(() async {
//             await Future.delayed(const Duration(microseconds: 100)).then((value) => const Home().launch(context));
//           }),
//           centerTitle: true,
//           iconTheme: const IconThemeData(color: Colors.white),
//           elevation: 0.0,
//         ),
//         body: WillPopScope(
//           onWillPop: () async {
//             await Future.delayed(const Duration(microseconds: 100)).then((value) {
//               if (mounted) {
//                 const Home().launch(context);
//                 return true;
//               } else {
//                 return false;
//               }
//             });
//             return false;
//           },
//           child: Container(
//             alignment: Alignment.topCenter,
//             decoration: const BoxDecoration(
//                 color: Colors.white,
//                 borderRadius: BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30))),
//             child: SingleChildScrollView(
//               child: Column(
//                 children: [
//                   const SizedBox(
//                     height: 10.0,
//                   ),
//                   TabBar(
//                     controller: tabController,
//                     tabAlignment: TabAlignment.start,
//                     indicatorSize: TabBarIndicatorSize.tab,
//                     labelColor: kMainColor,
//                     unselectedLabelColor: kGreyTextColor,
//                     onTap: (val) {
//                       setState(() {
//                         typeName = type[tabController!.index];
//                         typeIndex = tabController!.index;
//                       });
//                     },
//                     padding: EdgeInsets.zero,
//                     isScrollable: true,
//                     tabs: List.generate(
//                       type.length,
//                       (index) => Padding(
//                         padding: const EdgeInsets.all(10.0),
//                         child: Text(
//                           type[index],
//                           style: const TextStyle(fontSize: 18.0),
//                         ),
//                       ),
//                     ),
//                   ),
//                   const SizedBox(
//                     height: 10.0,
//                   ),
//                   Padding(
//                     padding: const EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 0.0),
//                     child: AppTextField(
//                       textFieldType: TextFieldType.NAME,
//                       onChanged: (value) {
//                         setState(() {
//                           partyName = value;
//                         });
//                       },
//                       decoration: InputDecoration(
//                           floatingLabelBehavior: FloatingLabelBehavior.never,
//                           //labelText: 'Party Name',
//                           labelText: lang.S.of(context).partyName,
//                           // hintText: 'Enter Party Name',
//                           hintText: lang.S.of(context).enterPartyName,
//                           border: const OutlineInputBorder(),
//                           prefixIcon: const Icon(Icons.search)),
//                     ),
//                   ),
//                   Padding(
//                     padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
//                     child: Consumer(
//                       builder: (context, ref, __) {
//                         final providerData = ref.watch(customerProvider);
//
//                         return providerData.when(
//                           data: (customer) {
//                             return customer.isNotEmpty
//                                 ? SizedBox(
//                                     height: customer.length * 73,
//                                     child: TabBarView(
//                                       controller: tabController,
//                                       children: [
//                                         ListView.builder(
//                                             shrinkWrap: true,
//                                             physics: const NeverScrollableScrollPhysics(),
//                                             itemCount: customer.length,
//                                             itemBuilder: (_, index) {
//                                               customer[index].type == 'Retailer'
//                                                   ? color = const Color(0xFF56da87)
//                                                   : Colors.white;
//                                               customer[index].type == 'Wholesaler'
//                                                   ? color = const Color(0xFF25a9e0)
//                                                   : Colors.white;
//                                               customer[index].type == 'Dealer'
//                                                   ? color = const Color(0xFFff5f00)
//                                                   : Colors.white;
//                                               customer[index].type == 'Supplier'
//                                                   ? color = const Color(0xFFA569BD)
//                                                   : Colors.white;
//
//                                               return Column(
//                                                 children: [
//                                                   GestureDetector(
//                                                     onTap: () {
//                                                       CustomerDetails(
//                                                         customerModel: customer[index],
//                                                       ).launch(context);
//                                                     },
//                                                     child: Visibility(
//                                                       visible: partyName.isEmptyOrNull
//                                                           ? true
//                                                           : customer[index]
//                                                                   .customerName
//                                                                   .toUpperCase()
//                                                                   .contains(partyName!.toUpperCase()) ||
//                                                               customer[index].phoneNumber.contains(partyName!),
//                                                       child: ListTile(
//                                                         horizontalTitleGap: 10,
//                                                         contentPadding: EdgeInsets.zero,
//                                                         leading: SizedBox(
//                                                           height: 50.0,
//                                                           width: 50.0,
//                                                           child: CircleAvatar(
//                                                             foregroundColor: Colors.blue,
//                                                             backgroundColor: kMainColor,
//                                                             radius: 70.0,
//                                                             child: ClipOval(
//                                                               child: Text(
//                                                                 customer[index].customerName.isNotEmpty
//                                                                     ? customer[index].customerName.substring(0, 1)
//                                                                     : '',
//                                                                 style: const TextStyle(
//                                                                     color: Colors.white, fontWeight: FontWeight.bold),
//                                                               ),
//                                                             ),
//                                                           ),
//                                                         ),
//                                                         title: Row(
//                                                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                           children: [
//                                                             Flexible(
//                                                               child: Text(
//                                                                 customer[index].customerName.isNotEmpty
//                                                                     ? customer[index].customerName
//                                                                     : customer[index].phoneNumber,
//                                                                 style: kTextStyle.copyWith(color: kTitleColor),
//                                                                 maxLines: 1,
//                                                                 overflow: TextOverflow.ellipsis,
//                                                               ),
//                                                             ),
//                                                             const SizedBox(width: 10),
//                                                             Visibility(
//                                                               visible: customer[index].dueAmount != '' &&
//                                                                   customer[index].dueAmount != '0',
//                                                               child: Text(
//                                                                 '$currency ${myFormat.format((customer[index].dueAmount ?? 0).toString().toDouble())}',
//                                                                 style: GoogleFonts.poppins(
//                                                                   color: Colors.black,
//                                                                   fontSize: 15.0,
//                                                                 ),
//                                                               ),
//                                                             ),
//
//                                                             // Visibility(
//                                                             //   visible: customer[index].dueAmount != '' && customer[index].dueAmount != '0',
//                                                             //   child: Text(
//                                                             //     '$currency ${myFormat.format(int.tryParse(customer[index].dueAmount.toString()) ?? 0)}',
//                                                             //     style: GoogleFonts.poppins(
//                                                             //       color: Colors.black,
//                                                             //       fontSize: 15.0,
//                                                             //     ),
//                                                             //   ),
//                                                             // ),
//                                                           ],
//                                                         ),
//                                                         subtitle: Row(
//                                                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                           children: [
//                                                             Text(
//                                                               customer[index].type,
//                                                               style: kTextStyle.copyWith(color: color, fontSize: 15.0),
//                                                             ),
//                                                             Visibility(
//                                                               visible: customer[index].dueAmount != '' &&
//                                                                   customer[index].dueAmount != '0',
//                                                               child: Text(
//                                                                 lang.S.of(context).due,
//                                                                 style: kTextStyle.copyWith(
//                                                                     color: const Color(0xFFff5f00), fontSize: 15),
//                                                               ),
//                                                             ),
//                                                           ],
//                                                         ),
//                                                         trailing: const Icon(
//                                                           Icons.arrow_forward_ios,
//                                                           color: kGreyTextColor,
//                                                         ),
//                                                       ),
//                                                     ),
//                                                   ),
//                                                   Divider(
//                                                     height: 1,
//                                                     thickness: 1.0,
//                                                     color: kBorderColor.withValues(alpha: 0.3),
//                                                   )
//                                                 ],
//                                               );
//                                             }),
//                                         ListView.builder(
//                                             itemCount: customer.length,
//                                             itemBuilder: (_, index) {
//                                               customer[index].type == 'Retailer'
//                                                   ? color = const Color(0xFF56da87)
//                                                   : Colors.white;
//                                               customer[index].type == 'Wholesaler'
//                                                   ? color = const Color(0xFF25a9e0)
//                                                   : Colors.white;
//                                               customer[index].type == 'Dealer'
//                                                   ? color = const Color(0xFFff5f00)
//                                                   : Colors.white;
//                                               customer[index].type == 'Supplier'
//                                                   ? color = const Color(0xFFA569BD)
//                                                   : Colors.white;
//                                               print('-------------customer model ${customer[index].type}');
//                                               return Column(
//                                                 children: [
//                                                   GestureDetector(
//                                                     onTap: () {
//                                                       CustomerDetails(
//                                                         customerModel: customer[index],
//                                                       ).launch(context);
//                                                     },
//                                                     child: Column(
//                                                       children: [
//                                                         ListTile(
//                                                           horizontalTitleGap: 10,
//                                                           contentPadding: EdgeInsets.zero,
//                                                           leading: SizedBox(
//                                                             height: 50.0,
//                                                             width: 50.0,
//                                                             child: CircleAvatar(
//                                                               foregroundColor: Colors.blue,
//                                                               backgroundColor: kMainColor,
//                                                               radius: 70.0,
//                                                               child: ClipOval(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName.substring(0, 1)
//                                                                       : '',
//                                                                   style: const TextStyle(
//                                                                       color: Colors.white, fontWeight: FontWeight.bold),
//                                                                 ),
//                                                               ),
//                                                             ),
//                                                           ),
//                                                           title: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Flexible(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName
//                                                                       : customer[index].phoneNumber,
//                                                                   style: kTextStyle.copyWith(color: kTitleColor),
//                                                                   maxLines: 1,
//                                                                   overflow: TextOverflow.ellipsis,
//                                                                 ),
//                                                               ),
//                                                               const SizedBox(width: 10),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   '$currency ${myFormat.format(customer[index].dueAmount.toString().toDouble())}',
//                                                                   style: GoogleFonts.poppins(
//                                                                     color: Colors.black,
//                                                                     fontSize: 15.0,
//                                                                   ),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           subtitle: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Text(
//                                                                 customer[index].type,
//                                                                 style:
//                                                                     kTextStyle.copyWith(color: color, fontSize: 15.0),
//                                                               ),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   lang.S.of(context).due,
//                                                                   style: kTextStyle.copyWith(
//                                                                       color: const Color(0xFFff5f00), fontSize: 15),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           trailing: const Icon(
//                                                             Icons.arrow_forward_ios,
//                                                             color: kGreyTextColor,
//                                                           ),
//                                                         ),
//                                                       ],
//                                                     ),
//                                                   ),
//                                                   Divider(
//                                                     height: 1,
//                                                     thickness: 1.0,
//                                                     color: kBorderColor.withValues(alpha: 0.3),
//                                                   )
//                                                 ],
//                                               ).visible(customer[index].type == 'Retailer');
//                                             }),
//                                         ListView.builder(
//                                             itemCount: customer.length,
//                                             itemBuilder: (_, index) {
//                                               customer[index].type == 'Retailer'
//                                                   ? color = const Color(0xFF56da87)
//                                                   : Colors.white;
//                                               customer[index].type == 'Wholesaler'
//                                                   ? color = const Color(0xFF25a9e0)
//                                                   : Colors.white;
//                                               customer[index].type == 'Dealer'
//                                                   ? color = const Color(0xFFff5f00)
//                                                   : Colors.white;
//                                               customer[index].type == 'Supplier'
//                                                   ? color = const Color(0xFFA569BD)
//                                                   : Colors.white;
//
//                                               return Column(
//                                                 children: [
//                                                   GestureDetector(
//                                                     onTap: () {
//                                                       CustomerDetails(
//                                                         customerModel: customer[index],
//                                                       ).launch(context);
//                                                     },
//                                                     child: Column(
//                                                       children: [
//                                                         ListTile(
//                                                           horizontalTitleGap: 10,
//                                                           contentPadding: EdgeInsets.zero,
//                                                           leading: SizedBox(
//                                                             height: 50.0,
//                                                             width: 50.0,
//                                                             child: CircleAvatar(
//                                                               foregroundColor: Colors.blue,
//                                                               backgroundColor: kMainColor,
//                                                               radius: 70.0,
//                                                               child: ClipOval(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName.substring(0, 1)
//                                                                       : '',
//                                                                   style: const TextStyle(
//                                                                       color: Colors.white, fontWeight: FontWeight.bold),
//                                                                 ),
//                                                               ),
//                                                             ),
//                                                           ),
//                                                           title: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Flexible(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName
//                                                                       : customer[index].phoneNumber,
//                                                                   style: kTextStyle.copyWith(color: kTitleColor),
//                                                                   maxLines: 1,
//                                                                   overflow: TextOverflow.ellipsis,
//                                                                 ),
//                                                               ),
//                                                               const SizedBox(width: 10),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   '$currency ${myFormat.format(customer[index].dueAmount.toDouble())}',
//                                                                   style: GoogleFonts.poppins(
//                                                                     color: Colors.black,
//                                                                     fontSize: 15.0,
//                                                                   ),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           subtitle: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Text(
//                                                                 customer[index].type,
//                                                                 style:
//                                                                     kTextStyle.copyWith(color: color, fontSize: 15.0),
//                                                               ),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   lang.S.of(context).due,
//                                                                   style: kTextStyle.copyWith(
//                                                                       color: const Color(0xFFff5f00), fontSize: 15),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           trailing: const Icon(
//                                                             Icons.arrow_forward_ios,
//                                                             color: kGreyTextColor,
//                                                           ),
//                                                         ),
//                                                       ],
//                                                     ),
//                                                   ),
//                                                   Divider(
//                                                     height: 1,
//                                                     thickness: 1.0,
//                                                     color: kBorderColor.withValues(alpha: 0.3),
//                                                   )
//                                                 ],
//                                               ).visible(customer[index].type == 'Supplier');
//                                             }),
//                                         ListView.builder(
//                                             itemCount: customer.length,
//                                             itemBuilder: (_, index) {
//                                               customer[index].type == 'Retailer'
//                                                   ? color = const Color(0xFF56da87)
//                                                   : Colors.white;
//                                               customer[index].type == 'Wholesaler'
//                                                   ? color = const Color(0xFF25a9e0)
//                                                   : Colors.white;
//                                               customer[index].type == 'Dealer'
//                                                   ? color = const Color(0xFFff5f00)
//                                                   : Colors.white;
//                                               customer[index].type == 'Supplier'
//                                                   ? color = const Color(0xFFA569BD)
//                                                   : Colors.white;
//
//                                               return Column(
//                                                 children: [
//                                                   GestureDetector(
//                                                     onTap: () {
//                                                       CustomerDetails(
//                                                         customerModel: customer[index],
//                                                       ).launch(context);
//                                                     },
//                                                     child: Column(
//                                                       children: [
//                                                         ListTile(
//                                                           horizontalTitleGap: 10,
//                                                           contentPadding: EdgeInsets.zero,
//                                                           leading: SizedBox(
//                                                             height: 50.0,
//                                                             width: 50.0,
//                                                             child: CircleAvatar(
//                                                               foregroundColor: Colors.blue,
//                                                               backgroundColor: kMainColor,
//                                                               radius: 70.0,
//                                                               child: ClipOval(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName.substring(0, 1)
//                                                                       : '',
//                                                                   style: const TextStyle(
//                                                                       color: Colors.white, fontWeight: FontWeight.bold),
//                                                                 ),
//                                                               ),
//                                                             ),
//                                                           ),
//                                                           title: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Flexible(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName
//                                                                       : customer[index].phoneNumber,
//                                                                   style: kTextStyle.copyWith(color: kTitleColor),
//                                                                   maxLines: 1,
//                                                                   overflow: TextOverflow.ellipsis,
//                                                                 ),
//                                                               ),
//                                                               const SizedBox(width: 10),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   '$currency ${myFormat.format(customer[index].dueAmount.toString().toDouble())}',
//                                                                   style: GoogleFonts.poppins(
//                                                                     color: Colors.black,
//                                                                     fontSize: 15.0,
//                                                                   ),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           subtitle: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Text(
//                                                                 customer[index].type,
//                                                                 style:
//                                                                     kTextStyle.copyWith(color: color, fontSize: 15.0),
//                                                               ),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   lang.S.of(context).due,
//                                                                   style: kTextStyle.copyWith(
//                                                                       color: const Color(0xFFff5f00), fontSize: 15),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           trailing: const Icon(
//                                                             Icons.arrow_forward_ios,
//                                                             color: kGreyTextColor,
//                                                           ),
//                                                         ),
//                                                       ],
//                                                     ),
//                                                   ),
//                                                   Divider(
//                                                     height: 1,
//                                                     thickness: 1.0,
//                                                     color: kBorderColor.withValues(alpha: 0.3),
//                                                   )
//                                                 ],
//                                               ).visible(customer[index].type == 'Wholesaler');
//                                             }),
//                                         ListView.builder(
//                                             itemCount: customer.length,
//                                             itemBuilder: (_, index) {
//                                               customer[index].type == 'Retailer'
//                                                   ? color = const Color(0xFF56da87)
//                                                   : Colors.white;
//                                               customer[index].type == 'Wholesaler'
//                                                   ? color = const Color(0xFF25a9e0)
//                                                   : Colors.white;
//                                               customer[index].type == 'Dealer'
//                                                   ? color = const Color(0xFFff5f00)
//                                                   : Colors.white;
//                                               customer[index].type == 'Supplier'
//                                                   ? color = const Color(0xFFA569BD)
//                                                   : Colors.white;
//
//                                               return Column(
//                                                 children: [
//                                                   GestureDetector(
//                                                     onTap: () {
//                                                       CustomerDetails(
//                                                         customerModel: customer[index],
//                                                       ).launch(context);
//                                                     },
//                                                     child: Column(
//                                                       children: [
//                                                         ListTile(
//                                                           horizontalTitleGap: 10,
//                                                           contentPadding: EdgeInsets.zero,
//                                                           leading: SizedBox(
//                                                             height: 50.0,
//                                                             width: 50.0,
//                                                             child: CircleAvatar(
//                                                               foregroundColor: Colors.blue,
//                                                               backgroundColor: kMainColor,
//                                                               radius: 70.0,
//                                                               child: ClipOval(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName.substring(0, 1)
//                                                                       : '',
//                                                                   style: const TextStyle(
//                                                                       color: Colors.white, fontWeight: FontWeight.bold),
//                                                                 ),
//                                                               ),
//                                                             ),
//                                                           ),
//                                                           title: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Flexible(
//                                                                 child: Text(
//                                                                   customer[index].customerName.isNotEmpty
//                                                                       ? customer[index].customerName
//                                                                       : customer[index].phoneNumber,
//                                                                   style: kTextStyle.copyWith(color: kTitleColor),
//                                                                   maxLines: 1,
//                                                                   overflow: TextOverflow.ellipsis,
//                                                                 ),
//                                                               ),
//                                                               const SizedBox(width: 10),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   '$currency ${myFormat.format(customer[index].dueAmount.toString().toDouble())}',
//                                                                   style: GoogleFonts.poppins(
//                                                                     color: Colors.black,
//                                                                     fontSize: 15.0,
//                                                                   ),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           subtitle: Row(
//                                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                                             children: [
//                                                               Text(
//                                                                 customer[index].type,
//                                                                 style:
//                                                                     kTextStyle.copyWith(color: color, fontSize: 15.0),
//                                                               ),
//                                                               Visibility(
//                                                                 visible: customer[index].dueAmount != '' &&
//                                                                     customer[index].dueAmount != '0',
//                                                                 child: Text(
//                                                                   lang.S.of(context).due,
//                                                                   style: kTextStyle.copyWith(
//                                                                       color: const Color(0xFFff5f00), fontSize: 15),
//                                                                 ),
//                                                               ),
//                                                             ],
//                                                           ),
//                                                           trailing: const Icon(
//                                                             Icons.arrow_forward_ios,
//                                                             color: kGreyTextColor,
//                                                           ),
//                                                         ),
//                                                       ],
//                                                     ),
//                                                   ),
//                                                   Divider(
//                                                     height: 1,
//                                                     thickness: 1.0,
//                                                     color: kBorderColor.withValues(alpha: 0.3),
//                                                   )
//                                                 ],
//                                               ).visible(customer[index].type == 'Dealer');
//                                             }),
//                                       ],
//                                     ),
//                                   )
//                                 : const Padding(
//                                     padding: EdgeInsets.only(top: 60),
//                                     child: EmptyScreenWidget(),
//                                   );
//                           },
//                           error: (e, stack) {
//                             return Text(e.toString());
//                           },
//                           loading: () {
//                             return const Center(child: CircularProgressIndicator());
//                           },
//                         );
//                       },
//                     ),
//                   ),
//                 ],
//               ),
//             ),
//           ),
//         ),
//         bottomNavigationBar: Container(
//           color: Colors.white,
//           child: ButtonGlobal(
//             iconWidget: Icons.add,
//             buttontext: lang.S.of(context).addCustomer,
//             iconColor: Colors.white,
//             buttonDecoration: kButtonDecoration.copyWith(
//                 color: kMainColor, borderRadius: const BorderRadius.all(Radius.circular(30))),
//             onPressed: () async {
//               if (await checkUserRolePermission(type: "customer-list-create")) {
//                 const AddCustomer(
//                   fromWhere: 'customer_list',
//                 ).launch(context);
//               }
//             },
//           ),
//         ),
//       ),
//     );
//   }
// }
