import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/Screens/Customers/add_customer.dart';
import 'package:mobile_pos/Screens/Purchase/add_purchase.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../Provider/add_to_cart_purchase.dart';
import '../../Provider/customer_provider.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../Customers/Model/customer_model.dart';

final purchaseContactsPaginationProvider =
    StateNotifierProvider<PurchaseContactsPaginationNotifier, PurchaseContactsPaginationState>(
        (ref) {
  return PurchaseContactsPaginationNotifier();
});

class PurchaseContactsPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<CustomerModel> displayedSuppliers;
  final String searchQuery;
  final bool hasAnySupplier;

  PurchaseContactsPaginationState({
    this.currentPage = 1,
    this.itemsPerPage = 10,
    this.isLoading = false,
    this.hasMore = true,
    List<CustomerModel>? displayedSuppliers,
    this.searchQuery = '',
    this.hasAnySupplier = false,
  }) : displayedSuppliers = displayedSuppliers ?? [];

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

class PurchaseContactsPaginationNotifier extends StateNotifier<PurchaseContactsPaginationState> {
  PurchaseContactsPaginationNotifier() : super(PurchaseContactsPaginationState());

  void resetPagination() {
    state = state.copyWith(
      currentPage: 1,
      displayedSuppliers: [],
      hasMore: true,
    );
  }

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

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

    state = state.copyWith(isLoading: true);

    final filteredSuppliers = _filterSuppliers(allCustomers);

    final hasAnySupplier = filteredSuppliers.isNotEmpty;

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

    final hasMoreItems = endIndex < totalItems;

    final nextBatch = endIndex <= totalItems
        ? filteredSuppliers.sublist(startIndex, endIndex)
        : filteredSuppliers.sublist(startIndex);

    final newDisplayedSuppliers = [...state.displayedSuppliers, ...nextBatch];

    state = state.copyWith(
      currentPage: state.currentPage + 1,
      isLoading: false,
      hasMore: hasMoreItems,
      displayedSuppliers: newDisplayedSuppliers,
      hasAnySupplier: hasAnySupplier,
    );
  }

  List<CustomerModel> _filterSuppliers(List<CustomerModel> customers) {
    return customers.where((customer) {
      if (!customer.type.contains('Supplier')) {
        return false;
      }

      if (state.searchQuery.isNotEmpty) {
        final matchesName =
            customer.customerName.toLowerCase().contains(state.searchQuery.toLowerCase());
        final matchesPhone =
            customer.phoneNumber.toLowerCase().contains(state.searchQuery.toLowerCase());
        return matchesName || matchesPhone;
      }

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

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

  @override
  State<PurchaseContacts> createState() => _PurchaseContactsState();
}

class _PurchaseContactsState extends State<PurchaseContacts> {
  Color color = Colors.black26;
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);

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

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      _loadMoreData();
    }
  }

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

    providerData.whenData((customers) {
      ref.read(purchaseContactsPaginationProvider.notifier).loadMoreSuppliers(customers);
    });
  }

  void _resetAndLoadData() {
    final ref = ProviderScope.containerOf(context);
    ref.read(purchaseContactsPaginationProvider.notifier).resetPagination();
    _loadMoreData();
  }

  void _debounceSearch() {
    Future.delayed(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          _searchQuery = _searchController.text;
        });
        final ref = ProviderScope.containerOf(context);
        ref.read(purchaseContactsPaginationProvider.notifier).updateSearchQuery(_searchQuery);
        _resetAndLoadData();
      }
    });
  }

  void _onSearchChanged(String value) {
    setState(() {
      _searchQuery = value;
    });
    final ref = ProviderScope.containerOf(context);
    ref.read(purchaseContactsPaginationProvider.notifier).updateSearchQuery(value);
    _resetAndLoadData();
  }

  Widget _buildSupplierListItem(CustomerModel customer, Color color) {
    return GestureDetector(
      onTap: () {
        AddPurchaseScreen(customerModel: customer).launch(context);
        final ref = ProviderScope.containerOf(context);
        ref.read(cartNotifierPurchase).clearCart();
      },
      child: Column(
        children: [
          ListTile(
            leading: SizedBox(
              height: 50.0,
              width: 50.0,
              child: CircleAvatar(
                foregroundColor: Colors.blue,
                backgroundColor: kMainColor,
                radius: 70.0,
                child: Text(
                  customer.customerName.isNotEmpty ? customer.customerName.substring(0, 1) : '',
                  style: const TextStyle(color: Colors.white),
                ),
              ),
            ),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Text(
                    customer.customerName.isNotEmpty
                        ? customer.customerName
                        : customer.phoneNumber,
                    style: GoogleFonts.poppins(
                      color: Colors.black,
                      fontSize: 15.0,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 10.0),
                Visibility(
                  visible: customer.dueAmount > 0,
                  child: Text(
                    '$currency ${myFormat.format(customer.dueAmount.toString().toDouble())}',
                    style: GoogleFonts.poppins(
                      color: Colors.black,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ],
            ),
            subtitle: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  customer.type,
                  style: GoogleFonts.poppins(
                    color: color,
                    fontSize: 15.0,
                  ),
                ),
                Visibility(
                  visible: customer.dueAmount != '' && customer.dueAmount != '0',
                  child: Text(
                    lang.S.of(context).due,
                    style: GoogleFonts.poppins(
                      color: const Color(0xFFff5f00),
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ],
            ),
            trailing: const Icon(
              Icons.arrow_forward_ios,
              color: kGreyTextColor,
            ),
            horizontalTitleGap: 10.0,
            contentPadding: const EdgeInsets.only(left: 8, right: 8.0),
          ),
          Divider(
            height: 1,
            thickness: 1.0,
            color: kBorderColor.withValues(alpha: 0.3),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, ref, __) {
      final providerData = ref.watch(customerProvider);
      final cart = ref.watch(cartNotifierPurchase);
      final paginationState = ref.watch(purchaseContactsPaginationProvider);

      return Scaffold(
        backgroundColor: kMainColor,
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          backgroundColor: kMainColor,
          title: Text(
            lang.S.of(context).choseASupplier,
            style: GoogleFonts.poppins(
              color: Colors.white,
            ),
          ),
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.white),
          elevation: 0.0,
        ),
        body: Container(
          alignment: Alignment.topCenter,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30))),
          child: providerData.when(
            data: (allCustomers) {
              // Initial load of data
              if (paginationState.displayedSuppliers.isEmpty && !paginationState.isLoading) {
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  _resetAndLoadData();
                });
              }

              final totalSuppliers =
                  allCustomers.where((customer) => customer.type.contains('Supplier')).length;
              final filteredSuppliers = allCustomers.where((customer) {
                if (!customer.type.contains('Supplier')) return false;
                if (_searchQuery.isNotEmpty) {
                  return customer.customerName
                          .toLowerCase()
                          .contains(_searchQuery.toLowerCase()) ||
                      customer.phoneNumber.toLowerCase().contains(_searchQuery.toLowerCase());
                }
                return true;
              }).toList();

              return Column(
                children: [
                  // Search Field
                  Padding(
                    padding: const EdgeInsets.all(10),
                    child: AppTextField(
                      controller: _searchController,
                      textFieldType: TextFieldType.NAME,
                      decoration: InputDecoration(
                        border: const OutlineInputBorder(),
                        hintText: lang.S.of(context).search,
                        prefixIcon: const Icon(Icons.search),
                      ),
                      onChanged: _onSearchChanged,
                    ),
                  ),

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

                                    final customer = paginationState.displayedSuppliers[index];
                                    color = const Color(0xFFA569BD); // Supplier color

                                    return _buildSupplierListItem(customer, color);
                                  },
                                ),
                              ],
                            ),
                          )
                        : _searchQuery.isNotEmpty
                            ? Center(
                                child: Padding(
                                  padding: const EdgeInsets.only(top: 60),
                                  child: Text(
                                    lang.S.of(context).noSupplierFound,
                                    style: const TextStyle(color: Colors.grey, fontSize: 16),
                                  ),
                                ),
                              )
                            : totalSuppliers == 0
                                ? const Padding(
                                    padding: EdgeInsets.only(top: 60),
                                    child: EmptyScreenWidget(),
                                  )
                                : const Center(
                                    child: CircularProgressIndicator(),
                                  ),
                  ),
                ],
              );
            },
            error: (e, stack) {
              return Center(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Text(
                    'Error loading suppliers: $e',
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                ),
              );
            },
            loading: () {
              return const Center(child: CircularProgressIndicator());
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.add),
          onPressed: () {
            const AddCustomer(fromWhere: "purchase").launch(context);
          },
        ),
      );
    });
  }
}
