import 'package:flutter/material.dart';
import 'package:flutter_cart/flutter_cart.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:flutter_svg/svg.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/Provider/product_provider.dart';
import 'package:mobile_pos/Screens/Customers/Model/customer_model.dart';
import 'package:mobile_pos/Screens/Sales/add_sales.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/constant.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../Provider/add_to_cart.dart';
import '../../currency.dart';
import '../../model/add_to_cart_model.dart';
import '../../model/product_model.dart';
import '../Warehouse/warehouse_model.dart';

// ignore: must_be_immutable
class SaleProducts extends ConsumerStatefulWidget {
  SaleProducts({super.key, @required this.catName, this.customerModel});

  // ignore: prefer_typing_uninitialized_variables
  var catName;
  CustomerModel? customerModel;

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

class _SaleProductsState extends ConsumerState<SaleProducts> {
  String dropdownValue = '';
  String productCode = '';

  String productName = '';

  var salesCart = FlutterCart();
  String productPrice = '0';
  String sentProductPrice = '';

  @override
  void initState() {
    widget.catName == null ? dropdownValue = 'Fashion' : dropdownValue = widget.catName;
    super.initState();
  }

  List<String> productCodeList = [];
  List<String> productNameList = [];

  TextEditingController scarchController = TextEditingController();
  List<ProductModel> showAbleProducts = [];
  final GlobalKey<FormState> _key = GlobalKey();

  List<AddToCartModel> cartList = [];

  dynamic productPriceChecker({required ProductModel product, required String customerType}) {
    if (customerType == "Retailer") {
      return product.productSalePrice;
    } else if (customerType == "Wholesaler") {
      return product.productWholeSalePrice == '' ? '0' : product.productWholeSalePrice;
    } else if (customerType == "Dealer") {
      return product.productDealerPrice == '' ? '0' : product.productDealerPrice;
    } else if (customerType == "Guest") {
      return product.productSalePrice;
    }
  }

  bool uniqueCheckForSerial({required String code, required List<dynamic> newSerialNumbers}) {
    bool isUnique = false;
    for (var item in cartList) {
      if (item.productId == code) {
        item.serialNumber = newSerialNumbers;
        item.quantity = newSerialNumbers.isEmpty ? 1 : newSerialNumbers.length;
        // item.serialNumber?.add(newSerialNumbers);

        isUnique = true;
        break;
      }
    }
    return isUnique;
  }

  String selectedCustomerType = 'Retailer';

  addFocus() {
    FocusNode f = FocusNode();
    f.addListener(() {
      if (!f.hasFocus) {
        setState(() {});
      }
    });
    productFocusNode.add(f);
  }

  List<FocusNode> productFocusNode = [];

  void showSerialNumberPopUp({required ProductModel productModel}) {
    AddToCartModel productInCart = AddToCartModel(
        productPurchasePrice: 0,
        serialNumber: [],
        productImage: '',
        warehouseName: '',
        warehouseId: '',
        subTaxes: [],
        excTax: 0,
        groupTaxName: '',
        groupTaxRate: 0,
        incTax: 0,
        margin: 0,
        taxType: '');
    List<dynamic> selectedSerialNumbers = [];
    List<String> list = [];
    for (var element in cartList) {
      if (element.productId == productModel.productCode) {
        productInCart = element;
        break;
      }
    }
    selectedSerialNumbers = productInCart.serialNumber ?? [];

    for (var element in productModel.serialNumber) {
      if (!selectedSerialNumbers.contains(element)) {
        list.add(element);
      }
    }
    TextEditingController editingController = TextEditingController();
    String searchWord = '';

    if (mounted) {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (context, setState1) {
              return Dialog(
                backgroundColor: Colors.white,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                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(
                            'Select Serial Number',
                            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),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AppTextField(
                            controller: editingController,
                            showCursor: true,
                            cursorColor: kTitleColor,
                            onChanged: (value) {
                              setState1(() {
                                searchWord = value;
                              });
                            },
                            onFieldSubmitted: (value) {
                              for (var element in list) {
                                if (value == element) {
                                  setState1(() {
                                    selectedSerialNumbers.add(element);
                                    editingController.clear();
                                    searchWord = '';
                                    list.removeWhere((element1) {
                                      return element1 == element;
                                    });
                                  });
                                  break;
                                }
                              }
                            },
                            textFieldType: TextFieldType.NAME,
                            suffix: const Icon(Icons.search),
                            decoration: kInputDecoration.copyWith(
                              border: const OutlineInputBorder(
                                  borderRadius: BorderRadius.all(Radius.circular(30))),
                              labelText: 'Search Serial Number',
                              hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              labelStyle: kTextStyle.copyWith(color: kTitleColor),
                            ),
                          ),
                          const SizedBox(height: 20),
                          Text('Serial Number List'),
                          const SizedBox(height: 10.0),
                          Container(
                            height: MediaQuery.of(context).size.height / 4,
                            width: 500,
                            decoration: BoxDecoration(
                              border: Border.all(width: 1, color: Colors.grey),
                              borderRadius: const BorderRadius.all(Radius.circular(10)),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: list.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Padding(
                                    padding: const EdgeInsets.only(bottom: 10),
                                    child: GestureDetector(
                                      onTap: () {
                                        setState1(() {
                                          selectedSerialNumbers.add(list[index]);
                                          list.removeAt(index);
                                        });
                                      },
                                      child: Text(list[index]),
                                    ),
                                  ).visible(list[index].contains(searchWord));
                                },
                              ),
                            ),
                          ),
                          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: selectedSerialNumbers.length,
                              itemBuilder: (BuildContext context, int index) {
                                print("serial number : ${selectedSerialNumbers[index]}");
                                if (selectedSerialNumbers.isNotEmpty) {
                                  return Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            setState1(() {
                                              list.add(selectedSerialNumbers[index]);
                                              selectedSerialNumbers.removeAt(index);
                                            });
                                          },
                                          child: const Icon(Icons.cancel_outlined, size: 15),
                                        ),
                                        SizedBox(width: 4),
                                        Text(selectedSerialNumbers[index],
                                            style: Theme.of(context)
                                                .textTheme
                                                .bodyMedium
                                                ?.copyWith(color: Colors.black)),
                                      ],
                                    ),
                                  );
                                } else {
                                  return Text('No Serial Number Found');
                                }
                              },
                              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                childAspectRatio: 4,
                                crossAxisSpacing: 5,
                                mainAxisSpacing: 5,
                                // mainAxisExtent: 1,
                              ),
                            ),
                          ),
                          const SizedBox(height: 20),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () => 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: Colors.red),
                                  child: Text(lang.S.of(context).cancel,
                                      style: kTextStyle.copyWith(color: kWhite)),
                                ),
                              ),
                              const SizedBox(width: 10.0),
                              GestureDetector(
                                // onTap: () {
                                //   setState(() {
                                //     AddToCartModel addToCartModel = AddToCartModel(
                                //       productName: productModel.productName,
                                //       warehouseName: productModel.warehouseName,
                                //       warehouseId: productModel.warehouseId,
                                //       productId: productModel.productCode,
                                //       productImage: productModel.productPicture,
                                //       productPurchasePrice: productModel.productPurchasePrice.toDouble(),
                                //       subTotal: productPriceChecker(product: productModel, customerType: selectedCustomerType),
                                //       serialNumber: selectedSerialNumbers,
                                //       quantity: selectedSerialNumbers.isEmpty ? 1 : selectedSerialNumbers.length,
                                //       stock: num.parse(productModel.productStock),
                                //       productWarranty: productModel.warranty,
                                //       subTaxes: productModel.subTaxes,
                                //       excTax: productModel.excTax,
                                //       groupTaxName: productModel.groupTaxName,
                                //       groupTaxRate: productModel.groupTaxRate,
                                //       incTax: productModel.incTax,
                                //       margin: productModel.margin,
                                //       taxType: productModel.taxType,
                                //     );
                                //     if (!uniqueCheckForSerial(code: productModel.productCode, newSerialNumbers: selectedSerialNumbers)) {
                                //       if (productModel.productStock == '0') {
                                //         EasyLoading.showError('Product Out Of Stock');
                                //       } else {
                                //         cartList.add(addToCartModel);
                                //         addFocus();
                                //       }
                                //     }
                                //   });
                                //   Navigator.pop(context);
                                // },
                                onTap: () {
                                  final providerData = ref.read(cartNotifier);
                                  AddToCartModel addToCartModel = AddToCartModel(
                                    uuid: productModel.productKey,
                                    productName: productModel.productName,
                                    warehouseName: productModel.warehouseName,
                                    warehouseId: productModel.warehouseId,
                                    productId: productModel.productCode,
                                    productImage: productModel.productPicture,
                                    productPurchasePrice:
                                        productModel.productPurchasePrice.toDouble(),
                                    subTotal: productPriceChecker(
                                        product: productModel, customerType: selectedCustomerType),
                                    serialNumber: selectedSerialNumbers,
                                    quantity: selectedSerialNumbers.isEmpty
                                        ? 1
                                        : selectedSerialNumbers.length,
                                    stock: num.parse(productModel.productStock),
                                    productWarranty: productModel.warranty,
                                    subTaxes: productModel.subTaxes,
                                    excTax: productModel.excTax,
                                    groupTaxName: productModel.groupTaxName,
                                    groupTaxRate: productModel.groupTaxRate,
                                    incTax: productModel.incTax,
                                    margin: productModel.margin,
                                    taxType: productModel.taxType,
                                  );

                                  if (!uniqueCheckForSerial(
                                      code: productModel.productCode,
                                      newSerialNumbers: selectedSerialNumbers)) {
                                    if (productModel.productStock == '0') {
                                      EasyLoading.showError('Product Out Of Stock');
                                    } else {
                                      /// 🔹 Push product into Riverpod provider (this will reflect in AddSalesScreen)
                                      providerData.addToCartRiverPod(addToCartModel);
                                      providerData.addProductsInSales(productModel);
                                      addFocus();
                                    }
                                  }
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => AddSalesScreen(
                                              customerModel: widget.customerModel!)));
                                },
                                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
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, ref, __) {
        List<WarehouseBasedProductModel> warehouseBasedProductModel = [];
        List<String> allWarehouseId = [];
        final providerData = ref.watch(cartNotifier);
        final productList = ref.watch(productProvider);
        final wareHouseList = ref.watch(warehouseProvider);
        return Scaffold(
          backgroundColor: kMainColor,
          appBar: AppBar(
            title: Text(lang.S.of(context).addItems,
                style: GoogleFonts.poppins(color: Colors.white, fontSize: 20.0)),
            iconTheme: const IconThemeData(color: Colors.white),
            centerTitle: true,
            backgroundColor: kMainColor,
            elevation: 0.0,
          ),
          body: Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
            ),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 10.0),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 3,
                        child: SizedBox(
                          height: 56.0,
                          child: Form(
                            key: _key,
                            child: TextFormField(
                              controller: scarchController,
                              onChanged: (value) {
                                setState(() {
                                  productCode = value;
                                  productName = value;
                                });
                              },
                              onSaved: (newValue) {
                                setState(() {
                                  productCode = newValue ?? '';
                                  productName = newValue ?? '';
                                });
                              },
                              decoration: InputDecoration(
                                floatingLabelBehavior: FloatingLabelBehavior.always,
                                //labelText: 'Product code/Name',
                                labelText: lang.S.of(context).productCode,
                                hintText: productCode.isEmpty
                                    ? lang.S.of(context).searchByProductCodeOrName
                                    : productCode,
                                border: const OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 10.0),
                      GestureDetector(
                        onTap: () async {
                          await showDialog(
                            barrierDismissible: true,
                            context: context,
                            builder: (context1) {
                              MobileScannerController controller =
                                  MobileScannerController(torchEnabled: false, returnImage: false);
                              return Container(
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadiusDirectional.circular(6.0)),
                                child: Column(
                                  children: [
                                    AppBar(
                                      backgroundColor: Colors.transparent,
                                      iconTheme: const IconThemeData(color: Colors.white),
                                      leading: IconButton(
                                        icon: const Icon(Icons.arrow_back),
                                        onPressed: () {
                                          Navigator.pop(context1);
                                        },
                                      ),
                                    ),
                                    Expanded(
                                      child: MobileScanner(
                                        fit: BoxFit.contain,
                                        controller: controller,
                                        onDetect: (capture) {
                                          final List<Barcode> barcodes = capture.barcodes;

                                          if (barcodes.isNotEmpty) {
                                            final Barcode barcode = barcodes.first;
                                            debugPrint('Barcode found! ${barcode.rawValue}');

                                            productCode = barcode.rawValue!;
                                            scarchController.text = productCode;
                                            _key.currentState!.save();

                                            Navigator.pop(context1);
                                          }
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          );
                        },
                        child: Container(
                          height: 56.0,
                          width: 56.0,
                          padding: const EdgeInsets.all(5.0),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5.0),
                            border: Border.all(color: kGreyTextColor),
                          ),
                          child: SvgPicture.asset('images/scan.svg',
                              height: 40.0,
                              width: 40.0,
                              allowDrawingOutsideViewBox: false,
                              fit: BoxFit.cover),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: productList.when(
                    data: (products) {
                      showAbleProducts.clear();
                      for (var element in products) {
                        // productNameList.add(element.productName.removeAllWhiteSpace().toLowerCase());
                        // productCodeList.add(element.productCode.removeAllWhiteSpace().toLowerCase());
                        warehouseBasedProductModel.add(
                            WarehouseBasedProductModel(element.productName, element.warehouseId));

                        allWarehouseId.add(element.warehouseId);
                        if (productCode != '' &&
                            (element.productName
                                    .removeAllWhiteSpace()
                                    .toLowerCase()
                                    .contains(productName.toString().toLowerCase()) ||
                                element.productCode.contains(productCode.toString()))) {
                          showAbleProducts.add(element);
                        } else if (productCode == '') {
                          showAbleProducts.add(element);
                        }
                      }
                      return showAbleProducts.isNotEmpty
                          ? ListView.builder(
                              padding: const EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 20.0),
                              shrinkWrap: true,
                              physics: const AlwaysScrollableScrollPhysics(),
                              itemCount: showAbleProducts.length,
                              itemBuilder: (_, i) {
                                // productCodeList.add(showAbleProducts[i].productCode.replaceAll(' ', '').toLowerCase());
                                // productNameList.add(showAbleProducts[i].productName.replaceAll(' ', '').toLowerCase());
                                if (widget.customerModel!.type.contains('Retailer')) {
                                  productPrice = showAbleProducts[i].productSalePrice;
                                } else if (widget.customerModel!.type.contains('Dealer')) {
                                  if (showAbleProducts[i].productDealerPrice == '') {
                                    productPrice = '0';
                                  } else {
                                    productPrice = showAbleProducts[i].productDealerPrice;
                                  }
                                } else if (widget.customerModel!.type.contains('Wholesaler')) {
                                  if (showAbleProducts[i].productWholeSalePrice == '') {
                                    productPrice = '0';
                                  } else {
                                    productPrice = showAbleProducts[i].productWholeSalePrice;
                                  }
                                } else if (widget.customerModel!.type.contains('Supplier')) {
                                  productPrice = showAbleProducts[i].productPurchasePrice;
                                } else if (widget.customerModel!.type.contains('Guest')) {
                                  productPrice = showAbleProducts[i].productSalePrice;
                                }
                                return GestureDetector(
                                  onTap: () async {
                                    if ((num.tryParse(showAbleProducts[i].productStock) ?? 0) <=
                                        0) {
                                      EasyLoading.showError(lang.S.of(context).outOfStock);
                                    } else {
                                      // 🔹 check if serial numbers exist
                                      if (showAbleProducts[i].serialNumber.isNotEmpty) {
                                        showSerialNumberPopUp(productModel: showAbleProducts[i]);
                                      } else {
                                        if (widget.customerModel!.type.contains('Retailer')) {
                                          sentProductPrice = showAbleProducts[i].productSalePrice;
                                        } else if (widget.customerModel!.type.contains('Dealer')) {
                                          sentProductPrice =
                                              showAbleProducts[i].productDealerPrice;
                                        } else if (widget.customerModel!.type
                                            .contains('Wholesaler')) {
                                          sentProductPrice =
                                              showAbleProducts[i].productWholeSalePrice;
                                        } else if (widget.customerModel!.type
                                            .contains('Supplier')) {
                                          sentProductPrice =
                                              showAbleProducts[i].productPurchasePrice;
                                        } else if (widget.customerModel!.type.contains('Guest')) {
                                          sentProductPrice = showAbleProducts[i].productSalePrice;
                                        }

                                        AddToCartModel cartItem = AddToCartModel(
                                            productName: showAbleProducts[i].productName,
                                            warehouseName: showAbleProducts[i].warehouseName,
                                            warehouseId: showAbleProducts[i].warehouseId,
                                            subTotal: sentProductPrice,
                                            productImage: showAbleProducts[i].productPicture,
                                            productPurchasePrice:
                                                showAbleProducts[i].productPurchasePrice,
                                            productId: showAbleProducts[i].productCode,
                                            productBrandName: showAbleProducts[i].brandName,
                                            stock: num.parse(showAbleProducts[i].productStock),
                                            uuid: showAbleProducts[i].productKey,
                                            subTaxes: showAbleProducts[i].subTaxes,
                                            excTax: showAbleProducts[i].excTax,
                                            groupTaxName: showAbleProducts[i].groupTaxName,
                                            groupTaxRate: showAbleProducts[i].groupTaxRate,
                                            incTax: showAbleProducts[i].incTax,
                                            margin: showAbleProducts[i].margin,
                                            taxType: showAbleProducts[i].taxType);

                                        providerData.addToCartRiverPod(cartItem);
                                        providerData.addProductsInSales(showAbleProducts[i]);
                                        Navigator.pop(context);
                                      }
                                    }
                                  },
                                  child: ProductCard(
                                          productTitle: showAbleProducts[i].productName,
                                          productDescription: showAbleProducts[i].brandName,
                                          productPrice: productPrice,
                                          productImage: showAbleProducts[i].productPicture,
                                          stock: showAbleProducts[i].productStock,
                                          productId: showAbleProducts[i].productCode,
                                          warehouseName: showAbleProducts[i].warehouseName)
                                      .visible(productName.isEmptyOrNull
                                          ? true
                                          : showAbleProducts[i]
                                                  .productName
                                                  .toUpperCase()
                                                  .contains(productName.toUpperCase()) ||
                                              (productName.isEmpty ||
                                                      productCode.isEmpty ||
                                                      showAbleProducts[i]
                                                          .productCode
                                                          .contains(productCode) ||
                                                      productCode == '0000' ||
                                                      productCode == '-1') &&
                                                  productPrice != '0'),
                                );
                              },
                            )
                          : Center(
                              // child: Text('No product Found'),
                              child: Text(lang.S.of(context).noProductFound),
                            );
                    },
                    error: (e, stack) {
                      return Text(e.toString());
                    },
                    loading: () {
                      return const Center(child: CircularProgressIndicator());
                    },
                  ),
                ),
              ],
            ),
          ),
          // bottomNavigationBar: ButtonGlobal(
          //   iconWidget: Icons.arrow_forward,
          //   buttontext: 'Sales List',
          //   iconColor: Colors.white,
          //   buttonDecoration: kButtonDecoration.copyWith(color: kMainColor),
          //   onPressed: () {
          //     // ignore: missing_required_param
          //     providerData.getTotalAmount() <= 0
          //         ? EasyLoading.showError('Cart Is Empty')
          //         : SalesDetails(
          //             customerName: widget.customerModel!.customerName,
          //           ).launch(context);
          //   },
          // ),
        );
      },
    );
  }
}

// ignore: must_be_immutable
class ProductCard extends StatefulWidget {
  ProductCard(
      {super.key,
      required this.productTitle,
      required this.productDescription,
      required this.productPrice,
      required this.productImage,
      required this.stock,
      required this.productId,
      required this.warehouseName});

  // final Product product;
  String productImage,
      productTitle,
      productDescription,
      productPrice,
      stock,
      productId,
      warehouseName;

  @override
  State<ProductCard> createState() => _ProductCardState();
}

class _ProductCardState extends State<ProductCard> {
  num quantity = 0;

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, ref, __) {
        final providerData = ref.watch(cartNotifier);
        for (var element in providerData.cartItemList) {
          if (element.productId == widget.productId) {
            quantity = element.quantity;
          }
        }
        return Column(
          children: [
            ListTile(
              contentPadding: EdgeInsets.zero,
              isThreeLine: false,
              dense: false,
              horizontalTitleGap: 10,
              leading: Container(
                height: 50,
                width: 50,
                decoration: BoxDecoration(
                  //image: DecorationImage(image: NetworkImage(widget.productImage), fit: BoxFit.cover),
                  borderRadius: BorderRadius.circular(90.0),
                  color: kMainColor,
                ),
                child: Center(
                  child: Text(
                    widget.productTitle.substring(0, 1),
                    style: const TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18),
                  ),
                ),
              ),
              title: Text(
                widget.productTitle,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: GoogleFonts.jost(fontSize: 16.0, color: Colors.black, height: 1.0),
              ),
              subtitle: Text(
                  '${lang.S.of(context).stock}: ${(num.tryParse(widget.stock) ?? 0) - quantity}',
                  style: GoogleFonts.jost(fontSize: 14.0, color: kGreyTextColor)),
              trailing: Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                        '$currency${myFormat.format(double.tryParse(widget.productPrice.toString()) ?? 0.0)}',
                        style: GoogleFonts.jost(fontSize: 18.0, color: Colors.black)),
                    Text(
                      widget.warehouseName,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: GoogleFonts.jost(fontSize: 14.0, color: kGreyTextColor),
                    ),
                  ],
                ),
              ),
            ),
            Divider(thickness: 1.0, height: 1.0, color: kBorderColor.withValues(alpha: 0.3)),
          ],
        );
      },
    );
  }
}

// class Bar extends StatefulWidget {
//   const Bar({super.key});
//
//   @override
//   State<Bar> createState() => _BarState();
// }
//
//
// class _BarState extends State<Bar> {
//   MobileScannerController controller = MobileScannerController(
//     torchEnabled: false,
//     returnImage: false,
//
//   );
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(title: const Text('Mobile Scanner')),
//       body: MobileScanner(
//
//
//         fit: BoxFit.contain,
//         controller: controller,
//         onDetect: (capture) {
//           final List<Barcode> barcodes = capture.barcodes;
//
//           // Check if there are any barcodes detected
//           if (barcodes.isNotEmpty) {
//             final Barcode barcode = barcodes.first;
//             debugPrint('Barcode found! ${barcode.rawValue}');
//             productCode = barcode.rawValue!;
//
//
//             // Check if the current context is on the top route before popping
//             if (Navigator.canPop(context)) {
//               Navigator.pop(context);
//             }
//           }
//         },
//         // onDetect: (capture) {
//         //   final List<Barcode> barcodes = capture.barcodes;
//         //   for (final barcode in barcodes) {
//         //     debugPrint('Barcode found! ${barcode.rawValue}');
//         //     productCode = barcode.rawValue!;
//         //     Navigator.pop(context);
//         //   }
//         // },
//       ),
//     );
//   }
// }
