import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/Screens/Due%20Calculation/due_collection_screen.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';
import '../Customers/Model/customer_model.dart';

final dueCalculationPaginationProvider =
    StateNotifierProvider<DueCalculationPaginationNotifier, DueCalculationPaginationState>((ref) {
  return DueCalculationPaginationNotifier();
});

class DueCalculationPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<CustomerModel> displayedCustomers;
  final bool hasAnyDue;

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

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

class DueCalculationPaginationNotifier extends StateNotifier<DueCalculationPaginationState> {
  DueCalculationPaginationNotifier() : super(DueCalculationPaginationState());

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

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

    state = state.copyWith(isLoading: true);

    final filteredCustomers = _filterCustomersWithDue(allCustomers);

    final hasAnyDue = filteredCustomers.isNotEmpty;

    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,
      hasAnyDue: hasAnyDue,
    );
  }

  List<CustomerModel> _filterCustomersWithDue(List<CustomerModel> customers) {
    return customers.where((customer) {
      return customer.dueAmount.toInt() > 0;
    }).toList();
  }
}

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

  @override
  State<DueCalculationContactScreen> createState() => _DueCalculationContactScreenState();
}

class _DueCalculationContactScreenState extends State<DueCalculationContactScreen> {
  late Color color;
  final ScrollController _scrollController = ScrollController();

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

  @override
  void 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(dueCalculationPaginationProvider.notifier).loadMoreCustomers(customers);
    });
  }

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

  Widget _buildCustomerListItem(CustomerModel customer, Color color) {
    return GestureDetector(
      onTap: () {
        DueCollectionScreen(customerModel: customer).launch(context);
      },
      child: Column(
        children: [
          ListTile(
            leading: SizedBox(
              height: 50.0,
              width: 50.0,
              child: CircleAvatar(
                foregroundColor: Colors.blue,
                backgroundColor: kMainColor,
                radius: 50.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,
                  ),
                ),
                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,
            ),
            contentPadding: const EdgeInsets.only(left: 8.0, right: 8.0),
          ),
          Divider(
            height: 1,
            thickness: 1.0,
            color: kBorderColor.withValues(alpha: 0.3),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kMainColor,
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        backgroundColor: kMainColor,
        title: Text(
          lang.S.of(context).dueList,
          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: Consumer(builder: (context, ref, __) {
          final providerData = ref.watch(customerProvider);
          final paginationState = ref.watch(dueCalculationPaginationProvider);

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

              final customersWithDue =
                  allCustomers.where((customer) => customer.dueAmount.toInt() > 0).toList();

              return paginationState.displayedCustomers.isNotEmpty || paginationState.isLoading
                  ? SingleChildScrollView(
                      controller: _scrollController,
                      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(),
                                        ),
                                      )
                                    : customersWithDue.isNotEmpty
                                        ? Padding(
                                            padding: const EdgeInsets.all(16.0),
                                            child: Center(
                                              child: Text(
                                                lang.S.of(context).noDataFound,
                                                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);
                            },
                          ),
                        ],
                      ),
                    )
                  : customersWithDue.isEmpty
                      ? const Center(
                          child: 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 due customers: $e',
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                ),
              );
            },
            loading: () {
              return const Center(child: CircularProgressIndicator());
            },
          );
        }),
      ),
    );
  }
}
