import 'dart:convert';
import 'dart:core';

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:hugeicons/hugeicons.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/customer_provider.dart';
import 'package:mobile_pos/Provider/transactions_provider.dart';
import 'package:mobile_pos/Screens/Purchase/purchase_products.dart';
import 'package:mobile_pos/Widget/utils.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:mobile_pos/model/product_model.dart';
import 'package:mobile_pos/model/transition_model.dart';
import 'package:mobile_pos/repository/category,brans,units_repo.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../Provider/add_to_cart_purchase.dart';
import '../../Provider/product_provider.dart';
import '../../Provider/profile_provider.dart';
import '../../Provider/purchase_report_provider.dart';
import '../../Services/check user subscription limit/check_subscription_limit_for_user.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../model/DailyTransactionModel.dart';
import '../../pdf/print_pdf.dart';
import '../../subscription.dart';
import '../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import '../Customers/Model/customer_model.dart';
import '../Home/home.dart';
import '../invoice_details/purchase_invoice_details.dart';

class AddPurchaseScreen extends ConsumerStatefulWidget {
  const AddPurchaseScreen({super.key, required this.customerModel});

  final CustomerModel customerModel;

  @override
  ConsumerState<AddPurchaseScreen> createState() => _AddPurchaseScreenState();
}

class _AddPurchaseScreenState extends ConsumerState<AddPurchaseScreen> {
  bool saleButtonClicked = false;
  TextEditingController paidText = TextEditingController();
  int invoice = 0;
  double paidAmount = 0;
  double discountAmount = 0;
  double returnAmount = 0;
  double dueAmount = 0;
  double subTotal = 0;
  String? selectedPaymanetType;
  List<String> paymentsTypesList = [];
  TextEditingController dateTextEditingController =
      TextEditingController(text: DateFormat.yMMMd().format(DateTime.now()));

  double calculateSubtotal({required double total}) {
    subTotal = total - discountAmount;
    return total - discountAmount;
  }

  double calculateReturnAmount({required double total}) {
    returnAmount = total - paidAmount;
    return paidAmount <= 0 || paidAmount <= subTotal ? 0 : total - paidAmount;
  }

  double calculateDueAmount({required double total}) {
    if (total < 0) {
      dueAmount = 0;
    } else {
      dueAmount = subTotal - paidAmount;
    }
    return returnAmount <= 0 ? 0 : subTotal - paidAmount;
  }

  late PurchaseTransactionModel transitionModel = PurchaseTransactionModel(
    customerName: widget.customerModel.customerName,
    customerAddress: widget.customerModel.customerAddress,
    customerPhone: widget.customerModel.phoneNumber,
    customerType: widget.customerModel.type,
    customerGst: widget.customerModel.gst,
    sendWhatsappMessage: widget.customerModel.receiveWhatsappUpdates ?? false,
    invoiceNumber: invoice.toString(),
    purchaseDate: DateTime.now().toString(),
  );

  // List<ProductModel> cartList = [];

  void productEditPopUp({required ProductModel product, required int index}) {
    FocusNode serialFocus = FocusNode();
    String editedPurchasePrice = '';
    String editedSalePrice = '';
    String editDealerPrice = '';
    String editWholesalerPrice = '';
    List<String> serialNumberList = product.serialNumber;
    TextEditingController serialController = TextEditingController();
    GlobalKey<FormState> priceKey = GlobalKey<FormState>();
    bool validateAndSave() {
      final form = priceKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    bool isWantToAddSerial = serialNumberList.isNotEmpty ? true : false;
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState1) {
            final cartData = ref.watch(cartNotifierPurchase);
            return Dialog(
              backgroundColor: Colors.white,
              surfaceTintColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: SizedBox(
                width: 500,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(
                                "${product.productName} (${product.productStock})",
                                style: kTextStyle.copyWith(
                                    color: kTitleColor,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20.0),
                              ),
                              const Spacer(),
                              const Icon(FeatherIcons.x, color: kTitleColor, size: 25.0)
                                  .onTap(() => {finish(context)})
                            ],
                          ),
                        ),
                        const Divider(thickness: 1.0, color: kGreyTextColor),
                        const SizedBox(height: 10.0),
                        Form(
                          key: priceKey,
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        if (value.isEmptyOrNull) {
                                          return 'Please enter Purchase Price';
                                        } else if (double.tryParse(value!) == null &&
                                            !value.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      initialValue: product.productPurchasePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editedPurchasePrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(
                                            borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).purchasePrice,
                                        hintText: lang.S.of(context).enterPurchasePrice,
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        if (value.isEmptyOrNull) {
                                          return 'Please enter Sale Price';
                                        } else if (double.tryParse(value!) == null &&
                                            !value.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      initialValue: product.productSalePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editedSalePrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(
                                            borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: 'Sales Price',
                                        hintText: 'Enter Sales Price',
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 20),
                              Row(
                                children: [
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        return null;
                                      },
                                      initialValue: product.productDealerPrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editDealerPrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(
                                            borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).dealerPrice,
                                        hintText: 'Enter Dealer Price',
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        return null;
                                      },
                                      initialValue: product.productWholeSalePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editWholesalerPrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(
                                            borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: 'WholeSale Price',
                                        hintText: 'Enter WholeSale Price',
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 20),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Row(
                            children: [
                              Text('Adding Serial Number'),
                              const SizedBox(width: 10),
                              Switch(
                                  value: isWantToAddSerial,
                                  onChanged: (value) {
                                    setState1(() {
                                      isWantToAddSerial = value;
                                    });
                                  })
                            ],
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // AppTextField(
                              //   controller: serialController,
                              //   focus: serialFocus,
                              //   autoFocus: true,
                              //   showCursor: true,
                              //   cursorColor: kTitleColor,
                              //   onFieldSubmitted: (value) {
                              //     if (!serialNumberList.contains(value)) {
                              //       setState1(() {
                              //         serialNumberList.add(value);
                              //         serialController.text = '';
                              //         serialFocus.requestFocus();
                              //       });
                              //     } else {
                              //       EasyLoading.showError('Already Added');
                              //       serialFocus.requestFocus();
                              //     }
                              //   },
                              //   textFieldType: TextFieldType.NAME,
                              //   decoration: kInputDecoration.copyWith(
                              //     border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                              //     labelText: 'Serial Number',
                              //     hintText: 'Enter Serial Number',
                              //     hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              //     labelStyle: kTextStyle.copyWith(color: kTitleColor),
                              //   ),
                              // ),
                              AppTextField(
                                controller: serialController,
                                focus: serialFocus,
                                autoFocus: true,
                                showCursor: true,
                                cursorColor: kTitleColor,
                                onFieldSubmitted: (value) {
                                  String trimmedValue = value.trim();
                                  // Case-insensitive duplicate check
                                  bool alreadyExists = serialNumberList.any(
                                    (element) =>
                                        element.toLowerCase().removeAllWhiteSpace() ==
                                        trimmedValue.toLowerCase().removeAllWhiteSpace(),
                                  );

                                  if (trimmedValue.isEmpty) {
                                    EasyLoading.showError('Please enter a serial number');
                                    serialFocus.requestFocus();
                                    return;
                                  }

                                  if (!alreadyExists) {
                                    setState1(() {
                                      serialNumberList.add(trimmedValue); // Keep the typed case
                                      serialController.clear();
                                      serialFocus.requestFocus();
                                    });
                                  } else {
                                    EasyLoading.showError('Already Added'); // Don't change serial
                                    serialFocus.requestFocus();
                                  }
                                },
                                textFieldType: TextFieldType.NAME,
                                decoration: kInputDecoration.copyWith(
                                  border: const OutlineInputBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(30)),
                                  ),
                                  labelText: 'Serial Number',
                                  hintText: 'Enter Serial Number',
                                  hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                  labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                ),
                              ),
                              const SizedBox(height: 20.0),
                              Text('Select Serial Number'),
                              const SizedBox(height: 10.0),
                              Container(
                                width: 500,
                                height: 100,
                                decoration: BoxDecoration(
                                    border: Border.all(width: 1, color: Colors.grey),
                                    borderRadius: const BorderRadius.all(Radius.circular(10))),
                                child: GridView.builder(
                                    shrinkWrap: true,
                                    itemCount: serialNumberList.length,
                                    itemBuilder: (BuildContext context, int index) {
                                      if (serialNumberList.isNotEmpty) {
                                        return Padding(
                                          padding: const EdgeInsets.all(10.0),
                                          child: Row(
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                '${serialNumberList[index]},',
                                              ),
                                              const SizedBox(width: 3),
                                              GestureDetector(
                                                  onTap: () {
                                                    setState1(() {
                                                      serialNumberList.removeAt(index);
                                                    });
                                                  },
                                                  child: const Icon(
                                                    Icons.close,
                                                    color: Colors.red,
                                                    size: 15,
                                                  )),
                                            ],
                                          ),
                                        );
                                      } else {
                                        return Text('No Serial Number Found');
                                      }
                                    },
                                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      childAspectRatio: 4,
                                      crossAxisSpacing: 1,
                                      mainAxisSpacing: 1,
                                      // mainAxisExtent: 1,
                                    )),
                              ),
                            ],
                          ),
                        ).visible(isWantToAddSerial),
                        const SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                                padding: const EdgeInsets.only(
                                    left: 30.0, right: 30.0, top: 10.0, bottom: 10.0),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5.0),
                                  color: Colors.red,
                                ),
                                child: Text(
                                  lang.S.of(context).cancel,
                                  style: kTextStyle.copyWith(color: kWhite),
                                )).onTap(() {
                              Navigator.pop(context);
                            }),
                            const SizedBox(width: 10.0),
                            GestureDetector(
                              // onTap: () {
                              //   if (validateAndSave()) {
                              //     cartData.cartItemPurchaseList[index].serialNumber = serialNumberList;
                              //     cartData.cartItemPurchaseList[index].productPurchasePrice = double.parse(editedPurchasePrice).toStringAsFixed(2);
                              //     cartData.cartItemPurchaseList[index].productSalePrice = double.parse(editedSalePrice).toStringAsFixed(2);
                              //     cartData.cartItemPurchaseList[index].productDealerPrice = double.parse(editDealerPrice).toStringAsFixed(2);
                              //     cartData.cartItemPurchaseList[index].productWholeSalePrice = double.parse(editWholesalerPrice).toStringAsFixed(2);
                              //
                              //     setState(() {});
                              //
                              //     Navigator.pop(context);
                              //   }
                              // },
                              onTap: () {
                                if (validateAndSave()) {
                                  // update cartData
                                  cartData.cartItemPurchaseList[index].serialNumber =
                                      List.from(serialNumberList);
                                  cartData.cartItemPurchaseList[index].productPurchasePrice =
                                      double.parse(editedPurchasePrice).toStringAsFixed(2);
                                  cartData.cartItemPurchaseList[index].productSalePrice =
                                      double.parse(editedSalePrice).toStringAsFixed(2);
                                  cartData.cartItemPurchaseList[index].productDealerPrice =
                                      double.parse(editDealerPrice).toStringAsFixed(2);
                                  cartData.cartItemPurchaseList[index].productWholeSalePrice =
                                      double.parse(editWholesalerPrice).toStringAsFixed(2);
                                  // also update the passed product model so providerData reflects it
                                  product.serialNumber = List.from(serialNumberList);
                                  product.productPurchasePrice =
                                      double.parse(editedPurchasePrice).toStringAsFixed(2);
                                  product.productSalePrice =
                                      double.parse(editedSalePrice).toStringAsFixed(2);
                                  product.productDealerPrice =
                                      double.parse(editDealerPrice).toStringAsFixed(2);
                                  product.productWholeSalePrice =
                                      double.parse(editWholesalerPrice).toStringAsFixed(2);

                                  // trigger UI update
                                  // setState(() {});
                                  ref.read(cartNotifierPurchase).updateCartItemAt(index, product);
                                  // If StateNotifierProvider:
                                  ref
                                      .read(cartNotifierPurchase.notifier)
                                      .updateCartItemAt(index, product);

                                  Navigator.pop(context);
                                }
                              },

                              child: Container(
                                padding: const EdgeInsets.only(
                                    left: 30.0, right: 30.0, top: 10.0, bottom: 10.0),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5.0),
                                  color: kMainColor,
                                ),
                                child: Text(
                                  lang.S.of(context).submit,
                                  style: kTextStyle.copyWith(color: kWhite),
                                ),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

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

  getPaymentsTypeList() async {
    await PaymentTypeRepo().getAllPaymentType().then((value) {
      paymentsTypesList.clear();
      for (var element in value) {
        paymentsTypesList.add(element.paymentTypeName);
      }
    });
    if (paymentsTypeList.isEmpty) {
      paymentsTypesList.add('Cash');
    }
    selectedPaymanetType = paymentsTypesList.isNotEmpty ? paymentsTypesList.first : null;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, consumerRef, __) {
      final providerData = consumerRef.watch(cartNotifierPurchase);
      final personalData = consumerRef.watch(profileDetailsProvider);
      return personalData.when(data: (data) {
        invoice = data.purchaseInvoiceCounter ?? 1;
        return Scaffold(
          backgroundColor: kMainColor,
          appBar: AppBar(
            backgroundColor: kMainColor,
            title: Text(
              lang.S.of(context).addPurchase,
              style: GoogleFonts.poppins(
                color: Colors.white,
              ),
            ),
            centerTitle: true,
            iconTheme: const IconThemeData(color: Colors.white),
            elevation: 0.0,
          ),
          body: Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(30), topLeft: Radius.circular(30))),
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: AppTextField(
                            textFieldType: TextFieldType.NAME,
                            readOnly: true,
                            initialValue: data.purchaseInvoiceCounter.toString(),
                            decoration: InputDecoration(
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              labelText: lang.S.of(context).invNo,
                              border: const OutlineInputBorder(),
                            ),
                          ),
                        ),
                        const SizedBox(width: 20),
                        Expanded(
                          child: AppTextField(
                            textFieldType: TextFieldType.NAME,
                            readOnly: true,
                            controller: dateTextEditingController,
                            // initialValue: DateFormat.yMMMd().format(selectedDate),

                            decoration: InputDecoration(
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              labelText: lang.S.of(context).date,
                              border: const OutlineInputBorder(),
                              suffixIcon: IconButton(
                                onPressed: () async {
                                  final DateTime? picked = await showDatePicker(
                                    initialDate: DateTime.now(),
                                    firstDate: DateTime(2015, 8),
                                    lastDate: DateTime(2101),
                                    context: context,
                                  );
                                  setState(() {
                                    dateTextEditingController.text =
                                        DateFormat.yMMMd().format(picked ?? DateTime.now());

                                    transitionModel.purchaseDate = picked.toString();
                                  });
                                },
                                icon: const Icon(FeatherIcons.calendar),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(lang.S.of(context).dueAmount),
                            Text(
                              widget.customerModel.dueAmount == ''
                                  ? '$currency 0'
                                  : '$currency${myFormat.format(int.tryParse(widget.customerModel.dueAmount.toString()) ?? 0)}',
                              style: const TextStyle(color: Color(0xFFFF8C34)),
                            ),
                          ],
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        AppTextField(
                          textFieldType: TextFieldType.NAME,
                          readOnly: true,
                          initialValue: widget.customerModel.customerName.isNotEmpty
                              ? widget.customerModel.customerName
                              : widget.customerModel.phoneNumber,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).supplierName,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),

                    ///_______Added_ItemS__________________________________________________
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10), topRight: Radius.circular(10)),
                        border: Border.all(width: 1, color: const Color(0xffEAEFFA)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                              width: double.infinity,
                              decoration: const BoxDecoration(
                                color: Color(0xffEAEFFA),
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(10), topRight: Radius.circular(10)),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.all(10),
                                child: SizedBox(
                                  width: context.width() / 1.35,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        lang.S.of(context).itemAdded,
                                        style: const TextStyle(fontSize: 16),
                                      ),
                                      Text(
                                        lang.S.of(context).quantity,
                                        style: const TextStyle(fontSize: 16),
                                      ),
                                    ],
                                  ),
                                ),
                              )),
                          ListView.builder(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemCount: providerData.cartItemPurchaseList.length,
                              itemBuilder: (context, index) {
                                return Padding(
                                  padding: const EdgeInsets.only(left: 10, right: 10),
                                  child: ListTile(
                                    contentPadding: const EdgeInsets.all(0),
                                    title: Text(providerData
                                        .cartItemPurchaseList[index].productName
                                        .toString()),
                                    subtitle: Row(
                                      children: [
                                        Text(
                                            '${providerData.cartItemPurchaseList[index].productStock} X ${myFormat.format(int.tryParse(providerData.cartItemPurchaseList[index].productPurchasePrice) ?? 0)} = ${myFormat.format(double.parse(providerData.cartItemPurchaseList[index].productStock) * providerData.cartItemPurchaseList[index].productPurchasePrice.toDouble())}'),
                                        SizedBox(width: 8),
                                        // Padding(
                                        //   padding: const EdgeInsets.only(top: 12),
                                        //   child: GestureDetector(
                                        //     onTap: () {
                                        //       productEditPopUp(product: cartList[index], index: index);
                                        //     },
                                        //     child: HugeIcon(
                                        //       icon: HugeIcons.strokeRoundedPropertyEdit,
                                        //       color: kMainColor,
                                        //       size: 16,
                                        //     ),
                                        //   ),
                                        // )
                                        Padding(
                                          padding: const EdgeInsets.only(top: 12),
                                          child: GestureDetector(
                                            onTap: () {
                                              if (index >= 0 &&
                                                  index <
                                                      providerData.cartItemPurchaseList.length) {
                                                productEditPopUp(
                                                    product:
                                                        providerData.cartItemPurchaseList[index],
                                                    index: index);
                                              } else {
                                                EasyLoading.showError("Invalid product selected!");
                                              }
                                            },
                                            child: HugeIcon(
                                              icon: HugeIcons.strokeRoundedPropertyEdit,
                                              color: kMainColor,
                                              size: 16,
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                    trailing: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        SizedBox(
                                          width: 80,
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              GestureDetector(
                                                onTap: () {
                                                  providerData.quantityDecrease(index);
                                                },
                                                child: Container(
                                                  height: 20,
                                                  width: 20,
                                                  decoration: const BoxDecoration(
                                                    color: kMainColor,
                                                    borderRadius:
                                                        BorderRadius.all(Radius.circular(10)),
                                                  ),
                                                  child: const Center(
                                                    child: Text(
                                                      '-',
                                                      style: TextStyle(
                                                          fontSize: 14, color: Colors.white),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              const SizedBox(width: 5),
                                              Text(
                                                providerData
                                                    .cartItemPurchaseList[index].productStock,
                                                style: GoogleFonts.poppins(
                                                  color: kGreyTextColor,
                                                  fontSize: 15.0,
                                                ),
                                              ),
                                              const SizedBox(width: 5),
                                              GestureDetector(
                                                onTap: () {
                                                  providerData.quantityIncrease(index);
                                                },
                                                child: Container(
                                                  height: 20,
                                                  width: 20,
                                                  decoration: const BoxDecoration(
                                                    color: kMainColor,
                                                    borderRadius:
                                                        BorderRadius.all(Radius.circular(10)),
                                                  ),
                                                  child: const Center(
                                                      child: Text(
                                                    '+',
                                                    style: TextStyle(
                                                        fontSize: 14, color: Colors.white),
                                                  )),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        const SizedBox(width: 10),
                                        GestureDetector(
                                          onTap: () {
                                            providerData.deleteToCart(index);
                                          },
                                          child: Container(
                                            padding: const EdgeInsets.all(4),
                                            color: Colors.red.withValues(alpha: 0.1),
                                            child: const Icon(
                                              Icons.delete,
                                              size: 20,
                                              color: Colors.red,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              }),
                        ],
                      ).visible(providerData.cartItemPurchaseList.isNotEmpty),
                    ),
                    const SizedBox(height: 20),

                    ///_______Add_Button__________________________________________________
                    GestureDetector(
                      onTap: () {
                        PurchaseProducts(
                          catName: null,
                          customerModel: widget.customerModel,
                        ).launch(context);
                      },
                      child: Container(
                        height: 50,
                        width: double.infinity,
                        decoration: BoxDecoration(
                            color: kMainColor.withValues(alpha: 0.1),
                            borderRadius: const BorderRadius.all(Radius.circular(10))),
                        child: Center(
                            child: Text(
                          lang.S.of(context).addItems,
                          style: const TextStyle(color: kMainColor, fontSize: 20),
                        )),
                      ),
                    ),
                    const SizedBox(height: 20),

                    ///_____Total______________________________
                    Container(
                      decoration: BoxDecoration(
                          borderRadius: const BorderRadius.all(Radius.circular(10)),
                          border: Border.all(color: Colors.grey.shade300, width: 1)),
                      child: Column(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(10),
                            decoration: const BoxDecoration(
                                color: Color(0xffEAEFFA),
                                borderRadius: BorderRadius.only(
                                    topRight: Radius.circular(10), topLeft: Radius.circular(10))),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).subTotal,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                Text(
                                  myFormat.format(providerData.getTotalAmount()),
                                  style: const TextStyle(fontSize: 16),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).discount,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                SizedBox(
                                  width: context.width() / 4,
                                  child: TextField(
                                    controller: paidText,
                                    onChanged: (value) {
                                      if (value == '') {
                                        setState(() {
                                          discountAmount = 0;
                                        });
                                      } else {
                                        if (value.toInt() <= providerData.getTotalAmount()) {
                                          setState(() {
                                            discountAmount = double.parse(value);
                                          });
                                        } else {
                                          paidText.clear();
                                          setState(() {
                                            discountAmount = 0;
                                          });
                                          //EasyLoading.showError('Enter a valid Discount');
                                          EasyLoading.showError(
                                              lang.S.of(context).enterAValidDiscount);
                                        }
                                      }
                                    },
                                    textAlign: TextAlign.right,
                                    decoration: const InputDecoration(
                                      hintText: '0',
                                    ),
                                    keyboardType: TextInputType.number,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).total,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                Text(
                                  myFormat.format(
                                      calculateSubtotal(total: providerData.getTotalAmount())),
                                  style: const TextStyle(fontSize: 16),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).paidAmount,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                SizedBox(
                                  width: context.width() / 4,
                                  child: TextField(
                                    keyboardType: TextInputType.number,
                                    onChanged: (value) {
                                      if (value == '') {
                                        setState(() {
                                          paidAmount = 0;
                                        });
                                      } else {
                                        setState(() {
                                          paidAmount = double.parse(value);
                                        });
                                      }
                                    },
                                    textAlign: TextAlign.right,
                                    decoration: const InputDecoration(hintText: '0'),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).returnAMount,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                Text(
                                  myFormat.format(calculateReturnAmount(total: subTotal).abs()),
                                  style: const TextStyle(fontSize: 16),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  lang.S.of(context).dueAmount,
                                  style: const TextStyle(fontSize: 16),
                                ),
                                Text(
                                  myFormat.format(calculateDueAmount(total: subTotal)),
                                  style: const TextStyle(fontSize: 16),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 20),
                    Container(
                      height: 1,
                      width: double.infinity,
                      color: Colors.grey,
                    ),
                    const SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text(
                              lang.S.of(context).paymentType,
                              style: const TextStyle(fontSize: 16, color: Colors.black54),
                            ),
                            const SizedBox(
                              width: 5,
                            ),
                            const Icon(
                              Icons.wallet,
                              color: Colors.green,
                            )
                          ],
                        ),
                        DropdownButton(
                          value: selectedPaymanetType,
                          icon: const Icon(Icons.keyboard_arrow_down),
                          items: paymentsTypesList.map((String items) {
                            return DropdownMenuItem(
                              value: items,
                              child: Text(items),
                            );
                          }).toList(),
                          onChanged: (newValue) {
                            setState(() {
                              selectedPaymanetType = newValue.toString();
                            });
                          },
                        ),
                      ],
                    ),
                    const SizedBox(height: 10),
                    Container(
                      height: 1,
                      width: double.infinity,
                      color: Colors.grey,
                    ),
                    const SizedBox(
                      height: 30,
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: AppTextField(
                            textFieldType: TextFieldType.NAME,
                            onChanged: (value) {
                              setState(() {});
                            },
                            decoration: InputDecoration(
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              labelText: lang.S.of(context).describtion,
                              hintText: lang.S.of(context).addNote,
                              border: const OutlineInputBorder(),
                            ),
                          ),
                        ),
                        const SizedBox(width: 20),
                        Container(
                            height: 60,
                            width: 100,
                            decoration: BoxDecoration(
                                borderRadius: const BorderRadius.all(Radius.circular(10)),
                                color: Colors.grey.shade200),
                            child: Center(
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  const Icon(
                                    FeatherIcons.camera,
                                    color: Colors.grey,
                                  ),
                                  const SizedBox(width: 5),
                                  Text(
                                    lang.S.of(context).image,
                                    style: const TextStyle(color: Colors.grey, fontSize: 16),
                                  )
                                ],
                              ),
                            )),
                      ],
                    ).visible(false),
                    Row(
                      children: [
                        Expanded(
                            child: GestureDetector(
                          onTap: () async {
                            const Home().launch(context);
                          },
                          child: Container(
                            height: 60,
                            decoration: const BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.all(Radius.circular(30)),
                            ),
                            child: Center(
                              child: Text(
                                lang.S.of(context).cancel,
                                //'Cancel',
                                style: const TextStyle(fontSize: 18, color: Colors.white),
                              ),
                            ),
                          ),
                        )),
                        const SizedBox(width: 10),
                        Expanded(
                          child: GestureDetector(
                            onTap: saleButtonClicked
                                ? () {}
                                : () async {
                                    bool allowed = await SubscriptionService.checkLimit(
                                      type: SubscriptionLimitType.purchase,
                                      context: context,
                                    );
                                    if (allowed) {
                                      if (providerData.cartItemPurchaseList.isNotEmpty) {
                                        if (selectedPaymanetType == null) {
                                          EasyLoading.showError('Please Select a payment Type');
                                          return;
                                        }
                                        try {
                                          setState(() {
                                            saleButtonClicked = true;
                                          });
                                          EasyLoading.show(
                                              status: '${lang.S.of(context).loading}...',
                                              dismissOnTap: false);

                                          dueAmount <= 0
                                              ? transitionModel.isPaid = true
                                              : transitionModel.isPaid = false;
                                          dueAmount <= 0
                                              ? transitionModel.dueAmount = 0
                                              : transitionModel.dueAmount = dueAmount;
                                          returnAmount < 0
                                              ? transitionModel.returnAmount = returnAmount.abs()
                                              : transitionModel.returnAmount = 0;
                                          transitionModel.discountAmount = discountAmount;
                                          transitionModel.totalAmount = subTotal;
                                          transitionModel.productList =
                                              providerData.cartItemPurchaseList;
                                          transitionModel.paymentType = selectedPaymanetType;
                                          transitionModel.invoiceNumber = invoice.toString();
                                          DatabaseReference ref = FirebaseDatabase.instance
                                              .ref("$constUserId/Purchase Transition");
                                          ref.keepSynced(true);
                                          ref.push().set(transitionModel.toJson());
                                          final bool isConnected =
                                              await InternetConnection().hasInternetAccess;
                                          if (isConnected) {
                                            await GeneratePdfAndPrint().uploadPurchaseInvoice(
                                                personalInformationModel: data,
                                                purchaseTransactionModel: transitionModel);
                                            var subData =
                                                await Subscription.subscriptionEnabledChecker();
                                            if (subData &&
                                                (transitionModel.sendWhatsappMessage ?? false)) {
                                              try {
                                                EasyLoading.show(
                                                    status:
                                                        '${lang.S.of(context).sendingMessage}...',
                                                    dismissOnTap: true);
                                                await sendPurchaseSms(transitionModel);
                                                EasyLoading.dismiss();
                                              } catch (e) {
                                                EasyLoading.dismiss();
                                              }
                                            }
                                          }

                                          ///__________StockMange_________________________________________________-
                                          final stockRef = FirebaseDatabase.instance
                                              .ref('$constUserId/Products/');
                                          stockRef.keepSynced(true);
                                          for (var element in transitionModel.productList!) {
                                            var data = await stockRef
                                                .orderByChild('productCode')
                                                .equalTo(element.productCode)
                                                .once();
                                            final data2 =
                                                jsonDecode(jsonEncode(data.snapshot.value));
                                            String productPath =
                                                data.snapshot.value.toString().substring(1, 21);

                                            var data1 = await stockRef
                                                .child('$productPath/productStock')
                                                .get();
                                            int stock = int.parse(data1.value.toString());
                                            int remainStock = stock + element.productStock.toInt();

                                            stockRef.child(productPath).update({
                                              'productStock': '$remainStock',
                                              'productSalePrice': element.productSalePrice,
                                              'productPurchasePrice': element.productPurchasePrice,
                                              'productDealerPrice': element.productDealerPrice,
                                              'productWholeSalePrice':
                                                  element.productWholeSalePrice,
                                            });

                                            ///________daily_transactionModel_________________________________________________________________________

                                            DailyTransactionModel dailyTransaction =
                                                DailyTransactionModel(
                                              name: transitionModel.customerName,
                                              date: transitionModel.purchaseDate,
                                              type: 'Purchase',
                                              total: transitionModel.totalAmount!.toDouble(),
                                              paymentIn: 0,
                                              paymentOut: transitionModel.totalAmount!.toDouble() -
                                                  transitionModel.dueAmount!.toDouble(),
                                              remainingBalance:
                                                  transitionModel.totalAmount!.toDouble() -
                                                      transitionModel.dueAmount!.toDouble(),
                                              id: transitionModel.invoiceNumber,
                                              purchaseTransactionModel: transitionModel,
                                            );
                                            postDailyTransaction(
                                                dailyTransactionModel: dailyTransaction);

                                            ///________Update_Serial_Number____________________________________________________

                                            if (element.serialNumber.isNotEmpty) {
                                              var productOldSerialList =
                                                  data2[productPath]['serialNumber'] ?? [];

                                              List<dynamic> result =
                                                  productOldSerialList + element.serialNumber;
                                              stockRef.child(productPath).update({
                                                'serialNumber': result.map((e) => e).toList(),
                                              });
                                            }
                                          }
                                          // for (var element in providerData.cartItemPurchaseList) {
                                          //   increaseStock(productCode: element.productCode, productModel: element);
                                          // }
                                          // if (element.serialNumber!.isNotEmpty) {
                                          //   var productOldSerialList = data2[productPath]['serialNumber'];
                                          //
                                          //   List<dynamic> result = productOldSerialList.where((item) => !element.serialNumber!.contains(item)).toList();
                                          //   stockRef.child(productPath).update({
                                          //     'serialNumber': result.map((e) => e).toList(),
                                          //   });
                                          // }

                                          ///_______invoice_Update_____________________________________________
                                          final DatabaseReference personalInformationRef =
                                              // ignore: deprecated_member_use
                                              FirebaseDatabase.instance
                                                  .ref()
                                                  .child(constUserId)
                                                  .child('Personal Information');
                                          personalInformationRef.keepSynced(true);
                                          personalInformationRef
                                              .update({'purchaseInvoiceCounter': invoice + 1});

                                          ///________Subscription_____________________________________________________
                                          Subscription.decreaseSubscriptionLimits(
                                              itemType: 'purchaseNumber', context: context);

                                          ///_________DueUpdate______________________________________________________
                                          getSpecificCustomers(
                                              phoneNumber: widget.customerModel.phoneNumber,
                                              due: transitionModel.dueAmount!.toInt());

                                          ///________daily_transactionModel_________________________________________________________________________

                                          DailyTransactionModel dailyTransaction =
                                              DailyTransactionModel(
                                            name: transitionModel.customerName,
                                            date: transitionModel.purchaseDate,
                                            type: 'Purchase',
                                            total: transitionModel.totalAmount!.toDouble(),
                                            paymentIn: 0,
                                            paymentOut: transitionModel.totalAmount!.toDouble() -
                                                transitionModel.dueAmount!.toDouble(),
                                            remainingBalance:
                                                transitionModel.totalAmount!.toDouble() -
                                                    transitionModel.dueAmount!.toDouble(),
                                            id: transitionModel.invoiceNumber,
                                            purchaseTransactionModel: transitionModel,
                                          );
                                          postDailyTransaction(
                                              dailyTransactionModel: dailyTransaction);

                                          ///________Print_______________________________________________________
                                          if (isPrintEnable) {
                                            PrintPurchaseTransactionModel model =
                                                PrintPurchaseTransactionModel(
                                                    purchaseTransitionModel: transitionModel,
                                                    personalInformationModel: data);
                                            await consumerRef
                                                .watch(thermalPrinterProvider)
                                                .printPurchaseThermalInvoiceNow(
                                                    transaction: model,
                                                    productList:
                                                        model.purchaseTransitionModel!.productList,
                                                    context: context);
                                          } else {
                                            consumerRef.refresh(customerProvider);
                                            consumerRef.refresh(productProvider);
                                            consumerRef.refresh(purchaseReportProvider);
                                            consumerRef.refresh(purchaseTransitionProvider);
                                            consumerRef.refresh(profileDetailsProvider);
                                            EasyLoading.dismiss();
                                          }
                                          await Future.delayed(const Duration(milliseconds: 500))
                                              .then((value) => PurchaseInvoiceDetails(
                                                    transitionModel: transitionModel,
                                                    personalInformationModel: data,
                                                  ).launch(context));
                                        } catch (e) {
                                          setState(() {
                                            saleButtonClicked = false;
                                          });
                                          EasyLoading.showError(e.toString());
                                        }
                                      } else {
                                        EasyLoading.showError(lang.S.of(context).addProductFirst);
                                      }
                                    }
                                  },
                            child: Container(
                              height: 60,
                              decoration: const BoxDecoration(
                                color: kMainColor,
                                borderRadius: BorderRadius.all(Radius.circular(30)),
                              ),
                              child: Center(
                                child: Text(
                                  lang.S.of(context).save,
                                  //'Save',
                                  style: const TextStyle(fontSize: 18, color: Colors.white),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }, error: (e, stack) {
        return Center(
          child: Text(e.toString()),
        );
      }, loading: () {
        return const Center(child: CircularProgressIndicator());
      });
    });
  }

  void increaseStock({required String productCode, required ProductModel productModel}) async {
    final ref = FirebaseDatabase.instance.ref(constUserId).child('Products');
    ref.keepSynced(true);

    ref.orderByKey().get().then((value) {
      for (var element in value.children) {
        var data = jsonDecode(jsonEncode(element.value));
        if (data['productCode'] == productCode) {
          String? key = element.key;
          num previousStock = num.tryParse(element.child('productStock').value.toString()) ?? 0;
          print(previousStock);
          num remainStock = previousStock + (num.tryParse(productModel.productStock) ?? 0);
          ref.child(key!).update({
            'productSalePrice': productModel.productSalePrice,
            'productPurchasePrice': productModel.productPurchasePrice,
            'productWholeSalePrice': productModel.productWholeSalePrice,
            'productDealerPrice': productModel.productDealerPrice,
            'productStock': '$remainStock',
          });
        }
      }
    });
  }

  void getSpecificCustomers({required String phoneNumber, required int due}) async {
    final ref = FirebaseDatabase.instance.ref(constUserId).child('Customers');
    ref.keepSynced(true);
    String? key;

    ref.orderByKey().get().then((value) {
      for (var element in value.children) {
        var data = jsonDecode(jsonEncode(element.value));
        if (data['phoneNumber'] == phoneNumber) {
          key = element.key;
          int previousDue = element.child('due').value.toString().toInt();
          print(previousDue);
          int totalDue = previousDue + due;
          ref.child(key!).update({'due': '$totalDue'});
        }
      }
    });
  }
}
