import 'package:flutter/material.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/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../../../Provider/profile_provider.dart';
import '../../../../constant.dart';
import '../../../../currency.dart';
import '../../../../empty_screen_widget.dart';
import '../../../../model/transition_model.dart';
import '../../../model/print_transaction_model.dart';
import '../../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import '../../purchase return/purchase_return_details.dart';
import 'Provider/purchase_returns_provider.dart';

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

  @override
  // ignore: library_private_types_in_public_api
  _PurchaseReturnReportState createState() => _PurchaseReturnReportState();
}

class _PurchaseReturnReportState extends State<PurchaseReturnReport> {
  double getTotalReturnAmount(List<PurchaseTransactionModel> transitionModel) {
    double total = 0.0;
    for (var element in transitionModel) {
      total += element.totalAmount ?? 0;
    }
    return total;
  }

  double calculateTotalDue(List<dynamic> purchaseTransitionModel) {
    double total = 0.0;
    for (var element in purchaseTransitionModel) {
      total += element.dueAmount!;
    }
    return total;
  }

  String searchItem = '';
  DateTime fromDate = DateTime(2021);
  DateTime toDate = DateTime.now();

  // Pagination variables
  final ScrollController _scrollController = ScrollController();
  int _currentPage = 1;
  final int _pageSize = 10;
  List<PurchaseTransactionModel> _allTransactions = [];
  List<PurchaseTransactionModel> _displayedTransactions = [];

  @override
  void initState() {
    super.initState();
    _setupScrollController();
  }

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

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

  void _loadMoreData() {
    final startIndex = _currentPage * _pageSize;
    if (startIndex < _allTransactions.length) {
      setState(() {
        _currentPage++;
        final endIndex = (_currentPage * _pageSize).clamp(0, _allTransactions.length);
        _displayedTransactions = _allTransactions.sublist(0, endIndex);
      });
    }
  }

  void _resetPagination() {
    setState(() {
      _currentPage = 1;
      _displayedTransactions = _allTransactions.take(_pageSize).toList();
    });
  }

  void _filterTransactions(List<PurchaseTransactionModel> transactions) {
    setState(() {
      _allTransactions = transactions;
      _displayedTransactions = _allTransactions.take(_pageSize).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, ref, __) {
      final transactionReport = ref.watch(purchaseReturnProvider);
      return transactionReport.when(
        data: (transaction) {
          // Filter transactions based on search and date range
          List<PurchaseTransactionModel> filteredTransactions = [];
          for (var element in transaction.reversed.toList()) {
            if ((element.invoiceNumber.toLowerCase().contains(searchItem.toLowerCase()) ||
                element.customerName.toLowerCase().contains(searchItem.toLowerCase()))) {
              if ((fromDate.isBefore(DateTime.parse(element.purchaseDate)) ||
                      DateTime.parse(element.purchaseDate).isAtSameMomentAs(fromDate)) &&
                  (toDate.isAfter(DateTime.parse(element.purchaseDate)) ||
                      DateTime.parse(element.purchaseDate).isAtSameMomentAs(toDate))) {
                filteredTransactions.add(element);
              }
            }
          }

          // Update pagination when transactions change
          if (_allTransactions != filteredTransactions) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              _filterTransactions(filteredTransactions);
            });
          }

          final profile = ref.watch(profileDetailsProvider);
          return Scaffold(
            backgroundColor: kMainColor,
            appBar: AppBar(
              iconTheme: const IconThemeData(color: kWhite),
              title: Text(
                lang.S.of(context).purchaseReturnReport,
                style: GoogleFonts.poppins(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
              centerTitle: true,
              backgroundColor: kMainColor,
              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: Column(
                children: [
                  // Summary Section
                  if (_displayedTransactions.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: Container(
                        height: 100,
                        width: double.infinity,
                        decoration: BoxDecoration(
                            color: kMainColor.withValues(alpha: 0.1),
                            border: Border.all(width: 1, color: kMainColor),
                            borderRadius: const BorderRadius.all(Radius.circular(15))),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  myFormat
                                      .format(double.tryParse(transaction.length.toString()) ?? 0),
                                  style: const TextStyle(
                                    color: Colors.green,
                                    fontSize: 20,
                                  ),
                                ),
                                const SizedBox(height: 10),
                                Text(
                                  lang.S.of(context).totalReturns,
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              width: 1,
                              height: 60,
                              color: kMainColor,
                            ),
                            Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  '$currency${myFormat.format(double.tryParse(getTotalReturnAmount(transaction).toString()) ?? 0)}',
                                  style: const TextStyle(
                                    color: Colors.orange,
                                    fontSize: 20,
                                  ),
                                ),
                                const SizedBox(height: 10),
                                Text(
                                  lang.S.of(context).totalReturnAmount,
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),

                  // Transactions List
                  Expanded(
                    child: _displayedTransactions.isNotEmpty
                        ? ListView.builder(
                            controller: _scrollController,
                            shrinkWrap: true,
                            itemCount:
                                _displayedTransactions.length + 1, // +1 for loading indicator
                            itemBuilder: (context, index) {
                              // Show loading indicator at the end
                              if (index == _displayedTransactions.length) {
                                return _buildLoadingIndicator();
                              }

                              final transaction = _displayedTransactions[index];
                              return _buildTransactionItem(transaction, profile, context, ref);
                            },
                          )
                        : const Padding(
                            padding: EdgeInsets.only(top: 60),
                            child: EmptyScreenWidget(),
                          ),
                  ),
                ],
              ),
            ),
          );
        },
        error: (e, stack) {
          return Text(e.toString());
        },
        loading: () {
          return const Center(child: CircularProgressIndicator());
        },
      );
    });
  }

  Widget _buildTransactionItem(
    PurchaseTransactionModel transaction,
    AsyncValue profile,
    BuildContext context,
    WidgetRef ref,
  ) {
    return GestureDetector(
      onTap: () {
        PurchaseReturnDetails(
          transitionModel: transaction,
          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(
                        transaction.customerName.isNotEmpty
                            ? transaction.customerName
                            : transaction.customerPhone,
                        style: const TextStyle(fontSize: 16),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      '#${transaction.invoiceNumber}',
                      style: const TextStyle(color: Colors.black),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                          color: transaction.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(
                        transaction.dueAmount! <= 0
                            ? lang.S.of(context).paid
                            : lang.S.of(context).unpaid,
                        style: TextStyle(
                            color: transaction.dueAmount! <= 0
                                ? const Color(0xff0dbf7d)
                                : const Color(0xFFED1A3B)),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          DateFormat.yMMMd().format(DateTime.parse(transaction.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          DateFormat.jm().format(DateTime.parse(transaction.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 5),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Text(
                        '${lang.S.of(context).total} : $currency ${myFormat.format(transaction.totalAmount)}',
                        style: const TextStyle(color: Colors.grey),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        '${lang.S.of(context).paid} : $currency ${myFormat.format(transaction.totalAmount!.toDouble() - transaction.dueAmount!.toDouble())}',
                        style: const TextStyle(color: Colors.grey),
                      ),
                      const SizedBox(height: 3),
                      Text(
                        '${lang.S.of(context).due}: $currency ${myFormat.format(transaction.dueAmount)}',
                        style: const TextStyle(fontSize: 16),
                      ).visible(transaction.dueAmount!.toInt() != 0),
                    ]),
                    Row(
                      children: [
                        IconButton(
                            onPressed: () async {
                              PrintPurchaseReturnTransactionModel model =
                                  PrintPurchaseReturnTransactionModel(
                                      purchaseTransactionModel: transaction,
                                      personalInformationModel: profile.value!);
                              ref.read(thermalPrinterProvider).printPurchaseReturnInvoiceThermal(
                                  transaction: model, context: context);
                            },
                            icon: const Icon(
                              FeatherIcons.printer,
                              color: Colors.grey,
                            )),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: 0.5,
            width: context.width(),
            color: Colors.grey,
          )
        ],
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    // Show loading indicator only if there are more items to load
    if (_displayedTransactions.length < _allTransactions.length) {
      return const Padding(
        padding: EdgeInsets.all(16.0),
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return const SizedBox.shrink();
    }
  }
}
