import 'package:community_material_icon/community_material_icon.dart';
import 'package:firebase_database/firebase_database.dart';
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/Provider/transactions_provider.dart';
import 'package:mobile_pos/Screens/Purchase%20List/purchase_list_edit_screen.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/product_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../Provider/profile_provider.dart';
import '../../../constant.dart';
import '../../../model/print_transaction_model.dart';
import '../../Provider/add_to_cart_purchase.dart';
import '../../Provider/customer_provider.dart';
import '../../Provider/product_provider.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../generate_pdf.dart';
import '../../pdf/purchase_pdf.dart';
import '../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import '../Home/home.dart';
import '../invoice_details/purchase_invoice_details.dart';
import '../purchase return/purchase_return_screen.dart';

// Add these providers for pagination
final purchasePaginationProvider =
    StateNotifierProvider<PurchasePaginationNotifier, PurchasePaginationState>((ref) {
  return PurchasePaginationNotifier(ref);
});

class PurchasePaginationState {
  final List<dynamic> transactions;
  final bool isLoading;
  final bool hasMore;
  final int currentPage;
  final int itemsPerPage;

  PurchasePaginationState({
    this.transactions = const [],
    this.isLoading = false,
    this.hasMore = true,
    this.currentPage = 0,
    this.itemsPerPage = 10,
  });

  PurchasePaginationState copyWith({
    List<dynamic>? transactions,
    bool? isLoading,
    bool? hasMore,
    int? currentPage,
    int? itemsPerPage,
  }) {
    return PurchasePaginationState(
      transactions: transactions ?? this.transactions,
      isLoading: isLoading ?? this.isLoading,
      hasMore: hasMore ?? this.hasMore,
      currentPage: currentPage ?? this.currentPage,
      itemsPerPage: itemsPerPage ?? this.itemsPerPage,
    );
  }
}

class PurchasePaginationNotifier extends StateNotifier<PurchasePaginationState> {
  final Ref ref;

  PurchasePaginationNotifier(this.ref) : super(PurchasePaginationState());

  Future<void> loadMore() async {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    try {
      // Get all transactions from the provider
      final allTransactions = await ref.read(purchaseTransitionProvider.future);
      final reversedTransactions = allTransactions.reversed.toList();

      final startIndex = state.currentPage * state.itemsPerPage;
      final endIndex = startIndex + state.itemsPerPage;

      // Check if we have more data to load
      if (startIndex >= reversedTransactions.length) {
        state = state.copyWith(
          isLoading: false,
          hasMore: false,
        );
        return;
      }

      // Get the next chunk of data
      final newTransactions = reversedTransactions.sublist(
        startIndex,
        endIndex < reversedTransactions.length ? endIndex : reversedTransactions.length,
      );

      state = state.copyWith(
        transactions: [...state.transactions, ...newTransactions],
        currentPage: state.currentPage + 1,
        isLoading: false,
        hasMore: endIndex < reversedTransactions.length,
      );
    } catch (e) {
      state = state.copyWith(isLoading: false);
    }
  }

  void refresh() {
    state = PurchasePaginationState();
    loadMore();
  }

  void filterByInvoice(String invoiceNumber) {
    // This would need to be implemented based on your filtering requirements
    // For now, we'll just refresh the data
    refresh();
  }
}

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

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

class _PurchaseReportState extends State<PurchaseListScreen> {
  String? invoiceNumber;
  final ScrollController _scrollController = ScrollController();
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // We'll initialize the data in the build method using Consumer
    });
  }

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

  void _scrollListener() {
    if (_scrollController.offset >= _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      // Load more data when reaching the bottom
      // This will be handled in the Consumer widget
    }
  }

  void _performSearch(String value) {
    setState(() {
      invoiceNumber = value;
      _isSearching = value.isNotEmpty;
    });
  }

  @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).purchaseList,
            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, ref, __) {
          // Initialize data on first build
          WidgetsBinding.instance.addPostFrameCallback((_) {
            final paginationState = ref.read(purchasePaginationProvider);
            if (paginationState.transactions.isEmpty && !paginationState.isLoading) {
              ref.read(purchasePaginationProvider.notifier).refresh();
            }
          });

          final paginationState = ref.watch(purchasePaginationProvider);
          final personalData = ref.watch(profileDetailsProvider);
          final profile = ref.watch(profileDetailsProvider);
          final cart = ref.watch(cartNotifierPurchase);

          return Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(30), topLeft: Radius.circular(30))),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: AppTextField(
                    textFieldType: TextFieldType.NUMBER,
                    onChanged: _performSearch,
                    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)),
                  ),
                ),
                Expanded(
                  child: _buildTransactionList(paginationState, personalData, profile, cart, ref),
                ),
              ],
            ),
          );
        }),
      ),
    );
  }

  Widget _buildTransactionList(
    PurchasePaginationState paginationState,
    AsyncValue personalData,
    AsyncValue profile,
    dynamic cart,
    WidgetRef ref,
  ) {
    // Filter transactions if searching
    final displayedTransactions = _isSearching && invoiceNumber != null
        ? paginationState.transactions
            .where((transaction) => transaction.invoiceNumber.toString().contains(invoiceNumber!))
        : paginationState.transactions;

    if (paginationState.transactions.isEmpty && paginationState.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (displayedTransactions.isEmpty && !paginationState.isLoading) {
      return const Padding(
        padding: EdgeInsets.only(top: 60),
        child: EmptyScreenWidget(),
      );
    }

    return NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollEndNotification) {
          if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent - 50) {
            ref.read(purchasePaginationProvider.notifier).loadMore();
          }
        }
        return false;
      },
      child: ListView.builder(
        controller: _scrollController,
        shrinkWrap: true,
        itemCount: displayedTransactions.length + (paginationState.hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          // Show loading indicator at the end if there's more data
          if (index == displayedTransactions.length) {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: Center(
                child: paginationState.hasMore
                    ? const CircularProgressIndicator()
                    : Text(
                        lang.S.of(context).noDataFound,
                        style: const TextStyle(color: Colors.grey),
                      ),
              ),
            );
          }

          final transaction = displayedTransactions.elementAt(index);
          return _buildTransactionItem(transaction, personalData, profile, cart, ref, context);
        },
      ),
    );
  }

  Widget _buildTransactionItem(
    dynamic transaction,
    AsyncValue personalData,
    AsyncValue profile,
    dynamic cart,
    WidgetRef ref,
    BuildContext context,
  ) {
    return GestureDetector(
      onTap: () {
        PurchaseInvoiceDetails(
          personalInformationModel: profile.value!,
          transitionModel: transaction,
        ).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: [
                    SizedBox(
                      width: 240,
                      child: Text(
                        transaction.customerName.isNotEmpty
                            ? transaction.customerName
                            : transaction.customerPhone,
                        style: const TextStyle(fontSize: 16),
                      ),
                    ),
                    Text('#${transaction.invoiceNumber}'),
                  ],
                ),
                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: 10),
                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: 3),
                        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),
                      ],
                    ),
                    personalData.when(data: (data) {
                      return Row(
                        children: [
                          IconButton(
                              onPressed: () async {
                                ///________Print_______________________________________________________
                                PrintPurchaseTransactionModel model =
                                    PrintPurchaseTransactionModel(
                                        purchaseTransitionModel: transaction,
                                        personalInformationModel: data);
                                ref.read(thermalPrinterProvider).printPurchaseThermalInvoiceNow(
                                    transaction: model,
                                    productList: model.purchaseTransitionModel!.productList,
                                    context: context);
                              },
                              icon: const Icon(
                                FeatherIcons.printer,
                                color: Colors.grey,
                              )),
                          IconButton(
                              onPressed: () async {
                                if (await checkUserRolePermission(type: "purchase-update")) {
                                  cart.clearCart();
                                  PurchaseListEditScreen(
                                    transitionModel: transaction,
                                  ).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().generatePurchaseDocument(
                                    transaction,
                                    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: () {
                                    sharePurchasePDF(
                                        transactions: transaction,
                                        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: "purchase-delete")) {
                                      showDialog(
                                          context: context,
                                          builder: (dontext) => AlertDialog(
                                                title: Text(
                                                    '${lang.S.of(context).areYouSureToDeleteThisInvoice}?'),
                                                content: Text(
                                                  "${lang.S.of(context).theSaleWillBeDeletedAndAllTheDataWill}?",
                                                  maxLines: 5,
                                                ),
                                                actions: [
                                                  Text(lang.S.of(context).cancel)
                                                      .onTap(() => Navigator.pop(dontext)),
                                                  Padding(
                                                    padding: const EdgeInsets.all(20.0),
                                                    child: Text(
                                                      lang.S.of(context).yesDeleteForever,
                                                    ).onTap(() async {
                                                      for (ProductModel element
                                                          in transaction.productList!) {
                                                        decreaseStock(element.productCode,
                                                            element.productStock.toInt());
                                                      }
                                                      getSpecificCustomersDueUpdate(
                                                        phoneNumber: transaction.customerPhone,
                                                        isDuePaid: false,
                                                        due: transaction.dueAmount ?? 0,
                                                      );
                                                      updateFromShopRemainBalance(
                                                          isFromPurchase: true,
                                                          paidAmount:
                                                              (transaction.totalAmount ?? 0) -
                                                                  (transaction.dueAmount ?? 0),
                                                          t: ref);
                                                      DatabaseReference firebaseRef =
                                                          FirebaseDatabase.instance.ref(
                                                              "$constUserId/Purchase Transition/${transaction.key}");
                                                      firebaseRef.keepSynced(true);
                                                      await firebaseRef.remove();
                                                      ref.refresh(purchaseTransitionProvider);
                                                      ref.refresh(productProvider);
                                                      ref.refresh(customerProvider);
                                                      ref.refresh(profileDetailsProvider);
                                                      // Refresh pagination after deletion
                                                      ref
                                                          .read(
                                                              purchasePaginationProvider.notifier)
                                                          .refresh();
                                                      // ignore: use_build_context_synchronously
                                                      Navigator.pop(dontext);
                                                      Navigator.pop(bc);
                                                    }),
                                                  ),
                                                ],
                                              ));
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        CommunityMaterialIcons.delete,
                                        color: Colors.grey,
                                      ),
                                      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: "purchase-return-create")) {
                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => PurchaseReturnScreen(
                                              purchaseTransactionModel: transaction,
                                            ),
                                          ));
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        CommunityMaterialIcons.keyboard_return,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).purchaseReturn,
                                        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,
          )
        ],
      ),
    );
  }
}

// class PurchaseListScreen extends StatefulWidget {
//   const PurchaseListScreen({super.key});
//
//   @override
//   // ignore: library_private_types_in_public_api
//   _PurchaseReportState createState() => _PurchaseReportState();
// }
//
// class _PurchaseReportState extends State<PurchaseListScreen> {
//   String? invoiceNumber;
//
//   @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).purchaseList,
//             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, ref, __) {
//           final providerData = ref.watch(purchaseTransitionProvider);
//           final personalData = ref.watch(profileDetailsProvider);
//           final profile = ref.watch(profileDetailsProvider);
//           final cart = ref.watch(cartNotifierPurchase);
//
//           return Container(
//             alignment: Alignment.topCenter,
//             decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30))),
//             child: SingleChildScrollView(
//               child: Column(
//                 children: [
//                   Padding(
//                     padding: const EdgeInsets.all(20.0),
//                     child: AppTextField(
//                       textFieldType: TextFieldType.NUMBER,
//                       onChanged: (value) {
//                         setState(() {
//                           invoiceNumber = value;
//                         });
//                       },
//                       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)),
//                     ),
//                   ),
//                   providerData.when(data: (transaction) {
//                     final reTransaction = transaction.reversed.toList();
//                     return reTransaction.isNotEmpty
//                         ? ListView.builder(
//                             shrinkWrap: true,
//                             physics: const NeverScrollableScrollPhysics(),
//                             itemCount: reTransaction.length,
//                             itemBuilder: (context, index) {
//                               return GestureDetector(
//                                 onTap: () {
//                                   PurchaseInvoiceDetails(
//                                     personalInformationModel: profile.value!,
//                                     transitionModel: reTransaction[index],
//                                   ).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: [
//                                               SizedBox(
//                                                 width: 240,
//                                                 child: Text(
//                                                   reTransaction[index].customerName.isNotEmpty ? reTransaction[index].customerName : reTransaction[index].customerPhone,
//                                                   style: const TextStyle(fontSize: 16),
//                                                 ),
//                                               ),
//                                               Text('#${reTransaction[index].invoiceNumber}'),
//                                             ],
//                                           ),
//                                           const SizedBox(height: 10),
//                                           Row(
//                                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                                             children: [
//                                               Container(
//                                                 padding: const EdgeInsets.all(8),
//                                                 decoration: BoxDecoration(color: reTransaction[index].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(
//                                                   reTransaction[index].dueAmount! <= 0 ? lang.S.of(context).paid : lang.S.of(context).unpaid,
//                                                   style: TextStyle(color: reTransaction[index].dueAmount! <= 0 ? const Color(0xff0dbf7d) : const Color(0xFFED1A3B)),
//                                                 ),
//                                               ),
//                                               Column(
//                                                 crossAxisAlignment: CrossAxisAlignment.end,
//                                                 children: [
//                                                   Text(
//                                                     DateFormat.yMMMd().format(DateTime.parse(reTransaction[index].purchaseDate)),
//                                                     style: const TextStyle(color: Colors.grey),
//                                                   ),
//                                                   const SizedBox(height: 5),
//                                                   Text(
//                                                     DateFormat.jm().format(DateTime.parse(reTransaction[index].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(reTransaction[index].totalAmount)}',
//                                                     style: const TextStyle(color: Colors.grey),
//                                                   ),
//                                                   const SizedBox(height: 3),
//                                                   Text(
//                                                     '${lang.S.of(context).paid} : $currency ${myFormat.format(reTransaction[index].totalAmount!.toDouble() - reTransaction[index].dueAmount!.toDouble())}',
//                                                     style: const TextStyle(color: Colors.grey),
//                                                   ),
//                                                   const SizedBox(height: 3),
//                                                   Text(
//                                                     '${lang.S.of(context).due}: $currency ${myFormat.format(reTransaction[index].dueAmount)}',
//                                                     style: const TextStyle(fontSize: 16),
//                                                   ).visible(reTransaction[index].dueAmount!.toInt() != 0),
//                                                 ],
//                                               ),
//                                               personalData.when(data: (data) {
//                                                 return Row(
//                                                   children: [
//                                                     IconButton(
//                                                         onPressed: () async {
//                                                           ///________Print_______________________________________________________
//
//                                                           PrintPurchaseTransactionModel model = PrintPurchaseTransactionModel(purchaseTransitionModel: reTransaction[index], personalInformationModel: data);
//                                                           ref.watch(thermalPrinterProvider).printPurchaseThermalInvoiceNow(transaction: model, productList: model.purchaseTransitionModel!.productList, context: context);
//                                                         },
//                                                         icon: const Icon(
//                                                           FeatherIcons.printer,
//                                                           color: Colors.grey,
//                                                         )),
//                                                     IconButton(
//                                                         onPressed: () async {
//                                                           if (await checkUserRolePermission(type: "purchase-update")) {
//                                                             cart.clearCart();
//                                                             PurchaseListEditScreen(
//                                                               transitionModel: reTransaction[index],
//                                                             ).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().generatePurchaseDocument(
//                                                               transaction[index],
//                                                               data,
//                                                               context,
//                                                             ),
//                                                             // onTap: () async {
//                                                             //  await GeneratePdf1().generatePurchaseDocument(transaction[index], data, context,);
//                                                             //   finish(context);
//                                                             // },
//                                                             child: Row(
//                                                               children: [
//                                                                 const Icon(
//                                                                   Icons.picture_as_pdf,
//                                                                   color: Colors.grey,
//                                                                 ),
//                                                                 const SizedBox(
//                                                                   width: 10.0,
//                                                                 ),
//                                                                 Text(
//                                                                   lang.S.of(context).pdfView,
//                                                                   //'Pdf View',
//                                                                   style: kTextStyle.copyWith(color: kGreyTextColor),
//                                                                 ),
//                                                               ],
//                                                             ),
//                                                           ),
//                                                         ),
//                                                         PopupMenuItem(
//                                                           child: GestureDetector(
//                                                             onTap: () {
//                                                               sharePurchasePDF(transactions: transaction[index], personalInformation: data, context: context);
//                                                               // GeneratePdf().generatePurchaseDocument(transaction[index], data, context, share: true);
//                                                               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),
//                                                                 ),
//                                                               ],
//                                                             ),
//                                                           ),
//                                                         ),
//
//                                                         ///_______ List Delete_______________________________
//                                                         PopupMenuItem(
//                                                           child: GestureDetector(
//                                                             onTap: () async {
//                                                               if (await checkUserRolePermission(type: "purchase-delete")) {
//                                                                 showDialog(
//                                                                     context: context,
//                                                                     builder: (dontext) => AlertDialog(
//                                                                           // title: const Text('Are you sure to delete this invoice?'),
//                                                                           title: Text('${lang.S.of(context).areYouSureToDeleteThisInvoice}?'),
//                                                                           content: Text(
//                                                                             "${lang.S.of(context).theSaleWillBeDeletedAndAllTheDataWill}?",
//                                                                             // 'The sale will be deleted and all the data will be deleted about this purchase.Are you sure to delete this?',
//                                                                             maxLines: 5,
//                                                                           ),
//                                                                           actions: [
//                                                                             // const Text('Cancel').onTap(() => Navigator.pop(dontext)),
//                                                                             Text(lang.S.of(context).cancel).onTap(() => Navigator.pop(dontext)),
//                                                                             Padding(
//                                                                               padding: const EdgeInsets.all(20.0),
//                                                                               child: Text(
//                                                                                 lang.S.of(context).yesDeleteForever,
//                                                                                 //'Yes, Delete Forever'
//                                                                               ).onTap(() async {
//                                                                                 for (ProductModel element in reTransaction[index].productList!) {
//                                                                                   decreaseStock(element.productCode, element.productStock.toInt());
//                                                                                 }
//                                                                                 getSpecificCustomersDueUpdate(
//                                                                                   phoneNumber: reTransaction[index].customerPhone,
//                                                                                   isDuePaid: false,
//                                                                                   due: reTransaction[index].dueAmount ?? 0,
//                                                                                 );
//                                                                                 updateFromShopRemainBalance(isFromPurchase: true, paidAmount: (reTransaction[index].totalAmount ?? 0) - (reTransaction[index].dueAmount ?? 0), t: ref);
//                                                                                 DatabaseReference firebaseRef = FirebaseDatabase.instance.ref("$constUserId/Purchase Transition/${reTransaction[index].key}");
//                                                                                 firebaseRef.keepSynced(true);
//                                                                                 await firebaseRef.remove();
//                                                                                 ref.refresh(purchaseTransitionProvider);
//                                                                                 ref.refresh(productProvider);
//                                                                                 ref.refresh(customerProvider);
//                                                                                 ref.refresh(profileDetailsProvider);
//                                                                                 // ignore: use_build_context_synchronously
//                                                                                 Navigator.pop(dontext);
//                                                                                 Navigator.pop(bc);
//                                                                               }),
//                                                                             ),
//                                                                           ],
//                                                                         ));
//                                                               }
//                                                             },
//                                                             child: Row(
//                                                               children: [
//                                                                 const Icon(
//                                                                   CommunityMaterialIcons.delete,
//                                                                   color: Colors.grey,
//                                                                 ),
//                                                                 const SizedBox(
//                                                                   width: 10.0,
//                                                                 ),
//                                                                 Text(
//                                                                   lang.S.of(context).delete,
//                                                                   //'Delete',
//                                                                   style: kTextStyle.copyWith(color: kGreyTextColor),
//                                                                 ),
//                                                               ],
//                                                             ),
//                                                           ),
//                                                         ),
//
//                                                         ///_______Purchase_Return_______________________________
//                                                         PopupMenuItem(
//                                                           child: GestureDetector(
//                                                             onTap: () async {
//                                                               if (await checkUserRolePermission(type: "purchase-return-create")) {
//                                                                 Navigator.push(
//                                                                     context,
//                                                                     MaterialPageRoute(
//                                                                       builder: (context) => PurchaseReturnScreen(
//                                                                         purchaseTransactionModel: reTransaction[index],
//                                                                       ),
//                                                                     ));
//                                                               }
//                                                             },
//                                                             child: Row(
//                                                               children: [
//                                                                 const Icon(
//                                                                   CommunityMaterialIcons.keyboard_return,
//                                                                   color: Colors.grey,
//                                                                 ),
//                                                                 const SizedBox(width: 10.0),
//                                                                 Text(
//                                                                   lang.S.of(context).purchaseReturn,
//                                                                   //'Purchase Return',
//                                                                   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,
//                                     )
//                                   ],
//                                 ),
//                               ).visible(invoiceNumber.isEmptyOrNull ? true : reTransaction[index].invoiceNumber.toString().contains(invoiceNumber!));
//                             },
//                           )
//                         : const Padding(
//                             padding: EdgeInsets.only(top: 60),
//                             child: EmptyScreenWidget(),
//                           );
//                   }, error: (e, stack) {
//                     return Text(e.toString());
//                   }, loading: () {
//                     return const Center(child: CircularProgressIndicator());
//                   }),
//                 ],
//               ),
//             ),
//           );
//         }),
//       ),
//     );
//   }
// }
