import 'package:community_material_icon/community_material_icon.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/add_to_cart.dart';
import 'package:mobile_pos/Provider/customer_provider.dart';
import 'package:mobile_pos/Provider/product_provider.dart';
import 'package:mobile_pos/Provider/transactions_provider.dart';
import 'package:mobile_pos/Screens/Sales%20List/sales_report_edit_screen.dart';
import 'package:mobile_pos/Screens/sale%20return/sales_return_screen.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/print_transaction_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../Provider/profile_provider.dart';
import '../../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../generate_pdf.dart';
import '../../model/personal_information_model.dart';
import '../../model/transition_model.dart';
import '../../pdf/sales_pdf.dart';
import '../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import '../Home/home.dart';
import '../Sales/sale_returns/sale_return_functions.dart';
import '../invoice_details/sales_invoice_details_screen.dart';

final salesListPaginationProvider =
    StateNotifierProvider<SalesListPaginationNotifier, SalesListPaginationState>((ref) {
  return SalesListPaginationNotifier();
});

class SalesListPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<SalesTransitionModel> displayedSales;
  final String searchQuery;

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

  SalesListPaginationState copyWith({
    int? currentPage,
    int? itemsPerPage,
    bool? isLoading,
    bool? hasMore,
    List<SalesTransitionModel>? displayedSales,
    String? searchQuery,
  }) {
    return SalesListPaginationState(
      currentPage: currentPage ?? this.currentPage,
      itemsPerPage: itemsPerPage ?? this.itemsPerPage,
      isLoading: isLoading ?? this.isLoading,
      hasMore: hasMore ?? this.hasMore,
      displayedSales: displayedSales ?? this.displayedSales,
      searchQuery: searchQuery ?? this.searchQuery,
    );
  }
}

class SalesListPaginationNotifier extends StateNotifier<SalesListPaginationState> {
  SalesListPaginationNotifier() : super(SalesListPaginationState());

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

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

  void loadMoreSales(List<SalesTransitionModel> allSales) {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    final filteredSales = _filterSales(allSales);

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

    final hasMoreItems = endIndex < totalItems;

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

    // Update state
    final newDisplayedSales = [...state.displayedSales, ...nextBatch];

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

  List<SalesTransitionModel> _filterSales(List<SalesTransitionModel> sales) {
    return sales.where((sale) {
      // Apply search filter if query is provided
      if (state.searchQuery.isNotEmpty) {
        return sale.invoiceNumber.toString().contains(state.searchQuery) ||
            sale.customerName.toLowerCase().contains(state.searchQuery.toLowerCase()) ||
            sale.customerPhone.contains(state.searchQuery);
      }

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

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

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

class _SalesListScreenState extends State<SalesListScreen> {
  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(transitionProvider);

    providerData.whenData((sales) {
      ref.read(salesListPaginationProvider.notifier).loadMoreSales(sales.reversed.toList());
    });
  }

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

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

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

  Widget _buildSaleListItem(SalesTransitionModel sale, WidgetRef consumerRef,
      AsyncValue<PersonalInformationModel> profile) {
    return GestureDetector(
      onTap: () async {
        if (await checkUserRolePermission(type: "sale-list-read")) {
          SalesInvoiceDetails(
            transitionModel: sale,
            personalInformationModel: profile.value!,
          ).launch(context);
        }
      },
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(20),
            width: context.width(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Flexible(
                      child: Text(
                        sale.customerName.isNotEmpty ? sale.customerName : sale.customerPhone,
                        style: const TextStyle(fontSize: 16),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 10.0),
                    Text(
                      '#${sale.invoiceNumber}',
                      style: const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                          color: sale.dueAmount! <= 0
                              ? const Color(0xff0dbf7d).withValues(alpha: 0.1)
                              : const Color(0xFFED1A3B).withValues(alpha: 0.1),
                          borderRadius: const BorderRadius.all(Radius.circular(10))),
                      child: Text(
                        sale.dueAmount! <= 0 ? lang.S.of(context).paid : lang.S.of(context).unpaid,
                        style: TextStyle(
                            color: sale.dueAmount! <= 0
                                ? const Color(0xff0dbf7d)
                                : const Color(0xFFED1A3B)),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          DateFormat.yMMMd().format(DateTime.parse(sale.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          DateFormat.jm().format(DateTime.parse(sale.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${lang.S.of(context).total} : $currency ${myFormat.format(sale.totalAmount)}',
                          style: const TextStyle(color: Colors.grey),
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '${lang.S.of(context).paid} : $currency ${myFormat.format(sale.totalAmount!.toDouble() - sale.dueAmount!.toDouble())}',
                          style: const TextStyle(color: Colors.grey),
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '${lang.S.of(context).due}: $currency ${myFormat.format(sale.dueAmount)}',
                          style: const TextStyle(fontSize: 16),
                        ).visible(sale.dueAmount!.toInt() != 0),
                      ],
                    ),
                    profile.when(data: (data) {
                      return Row(
                        children: [
                          IconButton(
                            onPressed: () async {
                              PrintTransactionModel model = PrintTransactionModel(
                                  transitionModel: sale, personalInformationModel: data);
                              consumerRef
                                  .watch(thermalPrinterProvider)
                                  .printSalesThermalInvoiceNow(
                                      transaction: model,
                                      productList: model.transitionModel?.productList,
                                      context: context);
                            },
                            icon: const Icon(
                              FeatherIcons.printer,
                              color: Colors.grey,
                            ),
                          ),
                          IconButton(
                            onPressed: () async {
                              if (await checkUserRolePermission(type: "sale-list-update")) {
                                final cart = consumerRef.read(cartNotifier);
                                cart.clearCart();
                                SalesReportEditScreen(
                                  transitionModel: sale,
                                ).launch(context);
                              }
                            },
                            icon: const Icon(
                              FeatherIcons.edit,
                              color: Colors.grey,
                            ),
                          ),
                          PopupMenuButton(
                            offset: const Offset(0, 30),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            padding: EdgeInsets.zero,
                            itemBuilder: (BuildContext bc) => [
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () async => await GeneratePdf1().generateSaleDocument(
                                    sale,
                                    data,
                                    context,
                                  ),
                                  child: Row(
                                    children: [
                                      const Icon(
                                        Icons.picture_as_pdf,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).pdfView,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () {
                                    shareSalePDF(
                                      transactions: sale,
                                      personalInformation: data,
                                      context: context,
                                    );
                                    finish(context);
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        CommunityMaterialIcons.share,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).share,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () async {
                                    if (await checkUserRolePermission(type: "sale-list-delete")) {
                                      showDialog(
                                        context: context,
                                        builder: (context2) => AlertDialog(
                                          title: Text(
                                              '${lang.S.of(context).areYouSureToDeleteThisSale}?'),
                                          content: Text(
                                            '${lang.S.of(context).theSaleWillBeDeletedAndAllTheDataWillSale}?',
                                            maxLines: 5,
                                          ),
                                          actions: [
                                            Text(lang.S.of(context).cancel)
                                                .onTap(() => Navigator.pop(context2)),
                                            Padding(
                                              padding: const EdgeInsets.all(20.0),
                                              child: Text(lang.S.of(context).yesDeleteForever)
                                                  .onTap(() async {
                                                EasyLoading.show();

                                                DeleteInvoice delete = DeleteInvoice();

                                                await delete.editStockAndSerial(
                                                  saleTransactionModel: sale,
                                                );

                                                await delete.customerDueUpdate(
                                                  due: sale.dueAmount ?? 0,
                                                  phone: sale.customerPhone,
                                                );
                                                await delete.updateFromShopRemainBalance(
                                                  paidAmount: (sale.totalAmount ?? 0) -
                                                      (sale.dueAmount ?? 0),
                                                  isFromPurchase: false,
                                                );
                                                await delete.deleteDailyTransaction(
                                                    invoice: sale.invoiceNumber,
                                                    status: 'Sale',
                                                    field: "saleTransactionModel");
                                                DatabaseReference ref = FirebaseDatabase.instance.ref(
                                                    "${await getUserID()}/Sales Transition/${sale.key}");

                                                await ref.remove();
                                                consumerRef.refresh(transitionProvider);
                                                consumerRef.refresh(productProvider);
                                                consumerRef.refresh(customerProvider);
                                                consumerRef.refresh(profileDetailsProvider);
                                                EasyLoading.showSuccess(lang.S.of(context).done);
                                                Navigator.pop(context2);
                                                Navigator.pop(bc);
                                              }),
                                            ),
                                          ],
                                        ),
                                      );
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        Icons.delete,
                                        color: kGreyTextColor,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).delete,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () async {
                                    if (await checkUserRolePermission(
                                        type: "sale-return-create")) {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) =>
                                              SalesReturn(saleTransactionModel: sale),
                                        ),
                                      );
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        Icons.keyboard_return_outlined,
                                        color: kGreyTextColor,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).saleReturn,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                            onSelected: (value) {
                              Navigator.pushNamed(context, '$value');
                            },
                            child: const Icon(
                              FeatherIcons.moreVertical,
                              color: kGreyTextColor,
                            ),
                          ),
                        ],
                      );
                    }, error: (e, stack) {
                      return Text(e.toString());
                    }, loading: () {
                      return Text(lang.S.of(context).loading);
                    }),
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: 0.5,
            width: context.width(),
            color: Colors.grey,
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return await const Home().launch(context, isNewTask: true);
      },
      child: Scaffold(
        backgroundColor: kMainColor,
        appBar: AppBar(
          title: Text(
            lang.S.of(context).salesList,
            style: GoogleFonts.poppins(
              color: Colors.white,
              fontSize: 20.0,
            ),
          ),
          iconTheme: const IconThemeData(color: Colors.white),
          centerTitle: true,
          backgroundColor: kMainColor,
          elevation: 0.0,
        ),
        body: Consumer(builder: (context, consumerRef, __) {
          final providerData = consumerRef.watch(transitionProvider);
          final profile = consumerRef.watch(profileDetailsProvider);
          final paginationState = consumerRef.watch(salesListPaginationProvider);

          return 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: (allSales) {
                // Initial load of data
                if (paginationState.displayedSales.isEmpty && !paginationState.isLoading) {
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    _resetAndLoadData();
                  });
                }

                final filteredSales = allSales.where((sale) {
                  if (_searchQuery.isNotEmpty) {
                    return sale.invoiceNumber.toString().contains(_searchQuery) ||
                        sale.customerName.toLowerCase().contains(_searchQuery.toLowerCase()) ||
                        sale.customerPhone.contains(_searchQuery);
                  }
                  return true;
                }).toList();

                return Column(
                  children: [
                    // Search Field
                    Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: AppTextField(
                        controller: _searchController,
                        textFieldType: TextFieldType.NUMBER,
                        onChanged: _onSearchChanged,
                        decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.never,
                            labelText: lang.S.of(context).invoiceNumber,
                            hintText: lang.S.of(context).enterInvoiceNumber,
                            border: const OutlineInputBorder(),
                            prefixIcon: const Icon(Icons.search)),
                      ),
                    ),

                    // Sales List with Pagination
                    Expanded(
                      child: paginationState.displayedSales.isNotEmpty || paginationState.isLoading
                          ? SingleChildScrollView(
                              controller: _scrollController,
                              child: Column(
                                children: [
                                  ListView.builder(
                                    shrinkWrap: true,
                                    physics: const NeverScrollableScrollPhysics(),
                                    itemCount: paginationState.displayedSales.length +
                                        (paginationState.hasMore ? 1 : 0),
                                    itemBuilder: (context, index) {
                                      // Loading indicator at the end
                                      if (index == paginationState.displayedSales.length) {
                                        return paginationState.hasMore
                                            ? const Padding(
                                                padding: EdgeInsets.all(16.0),
                                                child: Center(
                                                  child: CircularProgressIndicator(),
                                                ),
                                              )
                                            : filteredSales.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 sale = paginationState.displayedSales[index];
                                      return _buildSaleListItem(sale, consumerRef, profile);
                                    },
                                  ),
                                ],
                              ),
                            )
                          : _searchQuery.isNotEmpty
                              ? Center(
                                  child: Padding(
                                    padding: const EdgeInsets.only(top: 60),
                                    child: Text(
                                      lang.S.of(context).noDataFound,
                                      style: const TextStyle(color: Colors.grey, fontSize: 16),
                                    ),
                                  ),
                                )
                              : allSales.isEmpty
                                  ? 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 sales: $e',
                      style: const TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                  ),
                );
              },
              loading: () {
                return const Center(child: CircularProgressIndicator());
              },
            ),
          );
        }),
      ),
    );
  }
}
