import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/Provider/add_to_cart.dart';
import 'package:mobile_pos/Screens/Customers/Model/customer_model.dart';
import 'package:mobile_pos/Screens/Customers/add_customer.dart';
import 'package:mobile_pos/Screens/Sales/add_sales.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/customer_provider.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';

final salesContactPaginationProvider =
    StateNotifierProvider<SalesContactPaginationNotifier, SalesContactPaginationState>((ref) {
  return SalesContactPaginationNotifier();
});

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

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

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

class SalesContactPaginationNotifier extends StateNotifier<SalesContactPaginationState> {
  SalesContactPaginationNotifier() : super(SalesContactPaginationState());

  void resetPagination() {
    state = SalesContactPaginationState();
  }

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

  void loadMoreCustomers(List<CustomerModel> allCustomers, {String searchQuery = ''}) {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    final filteredCustomers = _filterCustomers(allCustomers, searchQuery: searchQuery);

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

    final hasMoreItems = endIndex < totalItems;

    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, {String searchQuery = ''}) {
    return customers.where((customer) {
      if (customer.type.contains('Supplier')) {
        return false;
      }

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

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

class SalesContact extends StatefulWidget {
  const SalesContact({super.key, required this.isFromHome});

  final bool isFromHome;

  @override
  _SalesContactState createState() => _SalesContactState();
}

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

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

    // Debounce search
    _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(salesContactPaginationProvider.notifier).loadMoreCustomers(
            customers,
            searchQuery: _searchQuery,
          );
    });
  }

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

  void _debounceSearch() {
    // Debounce search to avoid too many rebuilds
    Future.delayed(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          _searchQuery = _searchController.text;
        });
        final ref = ProviderScope.containerOf(context);
        ref.read(salesContactPaginationProvider.notifier).updateSearchQuery(_searchQuery);
        _resetAndLoadData();
      }
    });
  }

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

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

        return Scaffold(
          backgroundColor: kMainColor,
          resizeToAvoidBottomInset: true,
          appBar: AppBar(
            backgroundColor: kMainColor,
            title: Text(lang.S.of(context).choseACustomer,
                style: GoogleFonts.poppins(color: Colors.white)),
            centerTitle: true,
            iconTheme: const IconThemeData(color: Colors.white),
            elevation: 0.0,
            automaticallyImplyLeading: widget.isFromHome ? false : true,
          ),
          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.displayedCustomers.isEmpty && !paginationState.isLoading) {
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    _resetAndLoadData();
                  });
                }

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

                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:
                              Icon(Icons.search, color: kGreyTextColor.withValues(alpha: 0.5)),
                        ),
                        onChanged: _onSearchChanged,
                      ),
                    ),

                    // Guest Customer Option
                    GestureDetector(
                      onTap: () {
                        CustomerModel guestModel = CustomerModel(
                          'Guest',
                          'Guest',
                          'Guest',
                          'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460__340.png',
                          'Guest',
                          'Guest',
                          0,
                          0,
                          0,
                          '',
                          gst: '',
                          receiveWhatsappUpdates: false,
                        );
                        AddSalesScreen(customerModel: guestModel).launch(context);
                        cart.clearCart();
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                const SizedBox(
                                  height: 50.0,
                                  width: 50.0,
                                  child: CircleAvatar(
                                    foregroundColor: Colors.blue,
                                    backgroundColor: kMainColor,
                                    radius: 70.0,
                                    child: Text('G', style: TextStyle(color: Colors.white)),
                                  ),
                                ),
                                const SizedBox(width: 10.0),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(lang.S.of(context).walkInCustomer,
                                        style: GoogleFonts.poppins(
                                            color: Colors.black, fontSize: 15.0)),
                                    Text(lang.S.of(context).guest,
                                        style: GoogleFonts.poppins(
                                            color: Colors.grey, fontSize: 15.0)),
                                  ],
                                ),
                                const Spacer(),
                                const SizedBox(width: 20),
                                const Icon(Icons.arrow_forward_ios, color: kGreyTextColor),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 8.0, right: 10.0),
                      child: Divider(
                          height: 1, thickness: 1.0, color: kBorderColor.withValues(alpha: 0.3)),
                    ),

                    // Customers List with Pagination
                    Expanded(
                      child: paginationState.displayedCustomers.isNotEmpty ||
                              paginationState.isLoading
                          ? SingleChildScrollView(
                              controller: _scrollController,
                              child: Column(
                                children: [
                                  ListView.builder(
                                    padding: const EdgeInsets.only(left: 8.0, right: 10.0),
                                    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(),
                                                ),
                                              )
                                            : totalFilteredCustomers > 0
                                                ? 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 Column(
                                        children: [
                                          GestureDetector(
                                            onTap: () {
                                              AddSalesScreen(customerModel: customer)
                                                  .launch(context);
                                              cart.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 &&
                                                            customer.dueAmount != 0,
                                                        child: Text(
                                                            '$currency ${myFormat.format(customer.dueAmount)}',
                                                            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),
                                                  contentPadding: EdgeInsets.zero,
                                                  horizontalTitleGap: 10,
                                                ),
                                              ],
                                            ),
                                          ),
                                          Divider(
                                              height: 1,
                                              thickness: 1.0,
                                              color: kBorderColor.withValues(alpha: 0.3)),
                                        ],
                                      );
                                    },
                                  ),
                                ],
                              ),
                            )
                          : _searchQuery.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());
              },
            ),
          ),
          floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: () {
              const AddCustomer(fromWhere: 'sales').launch(context);
            },
          ),
        );
      },
    );
  }
}
