import 'dart:async';
import 'dart:convert';
import 'package:firebase_core/firebase_core.dart' as firebase_core;
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_dropzone/flutter_dropzone.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:go_router/go_router.dart';
import 'package:iconly/iconly.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_for_web/image_picker_for_web.dart';
import 'package:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/Screen/tax%20rates/tax_model.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;

import '../../Provider/product_provider.dart';
import '../../commas.dart';
import '../../const.dart';
import '../../model/brands_model.dart';
import '../../model/category_model.dart';
import '../../model/product_model.dart';
import '../../model/unit_model.dart';
import '../WareHouse/warehouse_model.dart';
import '../Widgets/Constant Data/constant.dart';
import '../Widgets/dotted_border/dotted_border.dart';

class EditProduct extends StatefulWidget {
  const EditProduct(
      {super.key, required this.productModel, required this.groupTaxModel, required this.allProductsNameList});

  final ProductModel productModel;
  final List<String> allProductsNameList;
  final List<GroupTaxModel> groupTaxModel;

  @override
  State<EditProduct> createState() => _AddProductState();
}

class _AddProductState extends State<EditProduct> {
  GlobalKey<FormState> addProductFormKey = GlobalKey<FormState>();

  bool categoryValidateAndSave() {
    final form = addProductFormKey.currentState;
    if (form!.validate()) {
      form.save();
      return true;
    }
    return false;
  }

  TextEditingController itemCategoryController = TextEditingController();
  TextEditingController brandNameController = TextEditingController();
  TextEditingController unitNameController = TextEditingController();

  bool isSerialNumberTaken = false;
  String selectedTime = 'Year';
  List<String> warrantyTime = ['Day', 'Month', 'Year'];
  String productPicture = '';
  List<String> allNameInThisFile = [];
  List<String> allCodeInThisFile = [];
  List<String> allCategory = [];
  bool isSize = false;
  bool isColor = false;
  bool isWeight = false;
  bool isCapacity = false;
  bool isType = false;
  bool isWarranty = false;
  bool isSizedBoxShow = false;
  bool isColoredBoxShow = false;
  bool isWeightsBoxShow = false;
  bool isWarrantyBoxShow = false;
  bool isCapacityBoxShow = false;
  bool isTypeBoxShow = false;
  TextEditingController descriptionController = TextEditingController();
  int unitTime = 0;
  List<String> extraAddedUnits = [];
  Uint8List? image;
  late DropzoneViewController controller;
  Future<void> addCategoryShowPopUp(
      {required WidgetRef ref, required List<String> categoryNameList, required BuildContext addProductContext}) async {
    GlobalKey<FormState> categoryNameKey = GlobalKey<FormState>();
    bool categoryValidateAndSave() {
      final form = categoryNameKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    showDialog(
        barrierDismissible: false,
        context: addProductContext,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, setState1) {
            return Dialog(
              surfaceTintColor: kWhite,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
              child: SizedBox(
                width: 600,
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(4.0),
                            decoration: const BoxDecoration(shape: BoxShape.rectangle),
                            child: const Icon(
                              FeatherIcons.plus,
                              color: kTitleColor,
                            ),
                          ),
                          const SizedBox(width: 4.0),
                          Text(
                            lang.S.of(context).addItemCategory,
                            style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                          ),
                          const Spacer(),
                          const Icon(
                            FeatherIcons.x,
                            color: kTitleColor,
                            size: 21.0,
                          ).onTap(() {
                            itemCategoryController.clear();
                            isSize = false;
                            isColor = false;
                            isWeight = false;
                            isCapacity = false;
                            isType = false;
                            isWarranty = false;
                            finish(context);
                          })
                        ],
                      ),
                      const SizedBox(height: 20.0),
                      Divider(
                        thickness: 1.0,
                        color: kGreyTextColor.withOpacity(0.2),
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Text(
                            lang.S.of(context).categoryName,
                            style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                          ),
                          const SizedBox(width: 20),
                          Form(
                            key: categoryNameKey,
                            child: SizedBox(
                              width: 400,
                              child: TextFormField(
                                controller: itemCategoryController,
                                validator: (value) {
                                  if (value.isEmptyOrNull) {
                                    return 'Category name is required.';
                                  } else if (categoryNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                    return 'Category name is already exist.';
                                  } else {
                                    return null;
                                  }
                                },
                                showCursor: true,
                                cursorColor: kTitleColor,
                                decoration: kInputDecoration.copyWith(
                                  errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                  labelText: lang.S.of(context).categoryName,
                                  hintText: lang.S.of(context).enterCategoryName,
                                  hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 30.0),
                      Text(
                        lang.S.of(context).selectVariations,
                        style: kTextStyle.copyWith(color: kTitleColor, fontWeight: FontWeight.bold, fontSize: 18.0),
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isSize,
                                onChanged: (val) {
                                  setState1(
                                    () {
                                      isSize = val!;
                                    },
                                  );
                                },
                              ),
                              title: Text(lang.S.of(context).size),
                            ),
                          ),
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isColor,
                                onChanged: (val) {
                                  setState1(() {
                                    isColor = val!;
                                  });
                                },
                              ),
                              title: Text(lang.S.of(context).color),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isWeight,
                                onChanged: (val) {
                                  setState1(() {
                                    isWeight = val!;
                                  });
                                },
                              ),
                              title: Text(lang.S.of(context).wight),
                            ),
                          ),
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isCapacity,
                                onChanged: (val) {
                                  setState1(
                                    () {
                                      isCapacity = val!;
                                    },
                                  );
                                },
                              ),
                              title: Text(lang.S.of(context).capacity),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isType,
                                onChanged: (val) {
                                  setState1(
                                    () {
                                      isType = val!;
                                    },
                                  );
                                },
                              ),
                              title: Text(lang.S.of(context).type),
                            ),
                          ),
                          Expanded(
                            child: ListTile(
                              leading: Checkbox(
                                activeColor: kMainColor,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                value: isWarranty,
                                onChanged: (val) {
                                  setState1(
                                    () {
                                      isWarranty = val!;
                                    },
                                  );
                                },
                              ),
                              title: Text(lang.S.of(context).warranty),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 5.0),
                      Divider(
                        thickness: 1.0,
                        color: kGreyTextColor.withOpacity(0.2),
                      ),
                      const SizedBox(height: 5.0),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            padding: const EdgeInsets.all(10.0),
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kRedTextColor),
                            child: Text(
                              lang.S.of(context).cancel,
                              style: kTextStyle.copyWith(color: kWhite),
                            ),
                          ).onTap(() {
                            itemCategoryController.clear();
                            isSize = false;
                            isColor = false;
                            isWeight = false;
                            isCapacity = false;
                            isType = false;
                            isWarranty = false;

                            finish(context);
                          }),
                          const SizedBox(width: 5.0),
                          Container(
                            padding: const EdgeInsets.all(10.0),
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kGreenTextColor),
                            child: Text(
                              lang.S.of(context).submit,
                              style: kTextStyle.copyWith(color: kWhite),
                            ),
                          ).onTap(() async {
                            if (categoryValidateAndSave()) {
                              EasyLoading.show(status: 'Adding Category');
                              try {
                                final DatabaseReference categoryInformationRef =
                                    FirebaseDatabase.instance.ref().child(await getUserID()).child('Categories');
                                CategoryModel categoryModel = CategoryModel(
                                  categoryName: itemCategoryController.text,
                                  size: isSize,
                                  color: isColor,
                                  capacity: isCapacity,
                                  type: isType,
                                  weight: isWeight,
                                  warranty: isWarranty,
                                );

                                await categoryInformationRef.push().set(categoryModel.toJson());
                                ref.refresh(categoryProvider);

                                setState1(() {
                                  // selectedCategories = categoryModel.categoryName;
                                  isSizedBoxShow = isSize;
                                  isColoredBoxShow = isColor;
                                  isWeightsBoxShow = isWeight;
                                  isCapacityBoxShow = isCapacity;
                                  isTypeBoxShow = isType;
                                  isWarrantyBoxShow = isWarranty;
                                });

                                itemCategoryController.clear();
                                isSize = false;
                                isColor = false;
                                isWeight = false;
                                isCapacity = false;
                                isType = false;
                                isWarranty = false;
                                EasyLoading.showSuccess("Successfully Added");

                                finish(context);
                              } catch (e) {
                                EasyLoading.showError('Error');
                              }
                            }
                          })
                        ],
                      )
                    ],
                  ),
                ),
              ),
            );
          });
        });
  }

  Future<void> showBrandPopUp(
      {required WidgetRef ref, required List<String> brandNameList, required BuildContext addProductsContext}) async {
    GlobalKey<FormState> brandNameKey = GlobalKey<FormState>();
    bool brandValidateAndSave() {
      final form = brandNameKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    showDialog(
        barrierDismissible: false,
        context: addProductsContext,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, setState) {
            return Dialog(
              surfaceTintColor: kWhite,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              child: SizedBox(
                width: 600,
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(4.0),
                            decoration: const BoxDecoration(shape: BoxShape.rectangle),
                            child: const Icon(
                              FeatherIcons.plus,
                              color: kTitleColor,
                            ),
                          ),
                          const SizedBox(width: 4.0),
                          Text(
                            lang.S.of(context).addBrand,
                            style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                          ),
                          const Spacer(),
                          const Icon(
                            FeatherIcons.x,
                            color: kTitleColor,
                            size: 21.0,
                          ).onTap(() {
                            brandNameController.clear();
                            finish(context);
                          })
                        ],
                      ),
                      const SizedBox(height: 20.0),
                      Divider(
                        thickness: 1.0,
                        color: kGreyTextColor.withOpacity(0.2),
                      ),
                      const SizedBox(height: 10.0),
                      Row(
                        children: [
                          Text(
                            lang.S.of(context).brandName,
                            style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                          ),
                          const SizedBox(width: 50),
                          Form(
                            key: brandNameKey,
                            child: SizedBox(
                              width: 400,
                              child: TextFormField(
                                validator: (value) {
                                  if (value.isEmptyOrNull) {
                                    return 'Brand name is required.';
                                  } else if (brandNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                    return 'Brand name is already exist.';
                                  } else {
                                    return null;
                                  }
                                },
                                controller: brandNameController,
                                showCursor: true,
                                cursorColor: kTitleColor,
                                decoration: kInputDecoration.copyWith(
                                  errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                  labelText: lang.S.of(context).brandName,
                                  hintText: lang.S.of(context).enterBrandName,
                                  hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Divider(
                        thickness: 1.0,
                        color: kGreyTextColor.withOpacity(0.2),
                      ),
                      const SizedBox(height: 5.0),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            padding: const EdgeInsets.all(10.0),
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kRedTextColor),
                            child: Text(
                              lang.S.of(context).cancel,
                              style: kTextStyle.copyWith(color: kWhite),
                            ),
                          ).onTap(() {
                            brandNameController.clear();
                            finish(context);
                          }),
                          const SizedBox(
                            width: 5.0,
                          ),
                          Container(
                            padding: const EdgeInsets.all(10.0),
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kGreenTextColor),
                            child: Text(
                              lang.S.of(context).submit,
                              style: kTextStyle.copyWith(color: kWhite),
                            ),
                          ).onTap(() async {
                            if (brandValidateAndSave()) {
                              try {
                                EasyLoading.show(status: 'Adding Brand');
                                final DatabaseReference categoryInformationRef =
                                    FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands');
                                BrandsModel brandModel = BrandsModel(brandNameController.text);
                                await categoryInformationRef.push().set(brandModel.toJson());
                                ref.refresh(brandProvider);
                                setState(() {
                                  // selectedBrand = brandModel.brandName;
                                  // brandName.clear();
                                });
                                brandNameController.clear();
                                EasyLoading.showSuccess("Successfully Added");
                                finish(context);
                              } catch (e) {
                                EasyLoading.showError('Error');
                              }
                            }
                          })
                        ],
                      )
                    ],
                  ),
                ),
              ),
            );
          });
        });
  }

  void showUnitPopUp(
      {required WidgetRef ref, required List<String> unitNameList, required BuildContext addProductsContext}) {
    GlobalKey<FormState> unitNameKey = GlobalKey<FormState>();
    bool unitValidateAndSave() {
      final form = unitNameKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    showDialog(
        barrierDismissible: true,
        context: addProductsContext,
        builder: (BuildContext context) {
          return Dialog(
            surfaceTintColor: kWhite,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            child: SizedBox(
              width: 600,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(4.0),
                          decoration: const BoxDecoration(shape: BoxShape.rectangle),
                          child: const Icon(
                            FeatherIcons.plus,
                            color: kTitleColor,
                          ),
                        ),
                        const SizedBox(width: 4.0),
                        Text(
                          lang.S.of(context).addUnit,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        const Icon(
                          FeatherIcons.x,
                          color: kTitleColor,
                          size: 21.0,
                        ).onTap(() {
                          unitNameController.clear();
                          descriptionController.clear();
                          finish(context);
                        })
                      ],
                    ),
                    const SizedBox(height: 20.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 10.0),
                    Row(
                      children: [
                        Text(
                          lang.S.of(context).unitName,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                        ),
                        const SizedBox(width: 50),
                        Form(
                          key: unitNameKey,
                          child: SizedBox(
                            width: 400,
                            child: TextFormField(
                              validator: (value) {
                                if (value.isEmptyOrNull) {
                                  return 'Unit name is required.';
                                } else if (unitNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                  return 'Unit name is already exist.';
                                } else {
                                  return null;
                                }
                              },
                              controller: unitNameController,
                              showCursor: true,
                              cursorColor: kTitleColor,
                              decoration: kInputDecoration.copyWith(
                                errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                labelText: lang.S.of(context).unitName,
                                hintText: lang.S.of(context).enterUnitName,
                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 5.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 5.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kRedTextColor),
                          child: Text(
                            lang.S.of(context).cancel,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() {
                          unitNameController.clear();
                          finish(context);
                        }),
                        const SizedBox(width: 5.0),
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kGreenTextColor),
                          child: Text(
                            lang.S.of(context).submit,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() async {
                          if (unitValidateAndSave()) {
                            try {
                              EasyLoading.show(status: 'Adding Units');
                              final DatabaseReference categoryInformationRef =
                                  FirebaseDatabase.instance.ref().child(await getUserID()).child('Units');
                              UnitModel unitModel = UnitModel(unitNameController.text);
                              await categoryInformationRef.push().set(unitModel.toJson());
                              ref.refresh(unitProvider);
                              setState(() {
                                unitTime = 0;
                                extraAddedUnits.clear();
                              });
                              unitNameController.clear();
                              EasyLoading.showSuccess("Successfully Added");
                              finish(context);
                            } catch (e) {
                              EasyLoading.showError('Error');
                            }
                          }
                        })
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  Future<void> uploadFileWithDragAndDrop(Uint8List? bytesFromPicker) async {
    // File file = File(filePath);
    if (kIsWeb) {
      try {
        // File? file = await ImagePickerWeb.getImageAsFile();
        if (bytesFromPicker!.isNotEmpty) {
          EasyLoading.show(
            status: 'Uploading... ',
            dismissOnTap: false,
          );
        }

        var snapshot = await FirebaseStorage.instance
            .ref('Profile Picture/${DateTime.now().millisecondsSinceEpoch}')
            .putData(bytesFromPicker);
        var url = await snapshot.ref.getDownloadURL();
        EasyLoading.showSuccess('Upload Successful!');
        setState(() {
          image = bytesFromPicker;
          productPicture = url.toString();
        });
      } on firebase_core.FirebaseException catch (e) {
        EasyLoading.dismiss();
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.code.toString())));
      }
    }
  }

  Future<void> uploadFile() async {
    // File file = File(filePath);
    if (kIsWeb) {
      try {
        XFile? imageFile = await ImagePickerPlugin().getImageFromSource(source: ImageSource.gallery);
        Uint8List? bytesFromPicker = await imageFile?.readAsBytes();
        // File? file = await ImagePickerWeb.getImageAsFile();
        if (bytesFromPicker!.isNotEmpty) {
          EasyLoading.show(
            status: 'Uploading... ',
            dismissOnTap: false,
          );
        }
        var snapshot = await FirebaseStorage.instance
            .ref('Profile Picture/${DateTime.now().millisecondsSinceEpoch}')
            .putData(bytesFromPicker);
        var url = await snapshot.ref.getDownloadURL();
        EasyLoading.showSuccess('Upload Successful!');
        setState(() {
          image = bytesFromPicker;
          productPicture = url.toString();
        });
      } on firebase_core.FirebaseException catch (e) {
        EasyLoading.dismiss();
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.code.toString())));
      }
    }
  }

  TextEditingController productNameController = TextEditingController();
  TextEditingController productSalePriceController = TextEditingController();
  TextEditingController productPurchasePriceController = TextEditingController();
  TextEditingController productDiscountPriceController = TextEditingController();
  TextEditingController productWholesalePriceController = TextEditingController();
  TextEditingController productDealerPriceController = TextEditingController();
  TextEditingController productManufacturerController = TextEditingController();

  //------------product quantity controller--------------
  TextEditingController quantityController = TextEditingController();

  TextEditingController sizeController = TextEditingController();
  TextEditingController colorController = TextEditingController();
  TextEditingController weightController = TextEditingController();
  TextEditingController capacityController = TextEditingController();
  TextEditingController typeController = TextEditingController();
  TextEditingController warrantyController = TextEditingController();
  TextEditingController productSerialNumberController = TextEditingController(text: '');
  TextEditingController expireDateTextEditingController = TextEditingController();
  TextEditingController manufactureDateTextEditingController = TextEditingController();

  TextEditingController totalAmountController = TextEditingController();
  TextEditingController incTaxController = TextEditingController();
  TextEditingController excTaxController = TextEditingController();
  TextEditingController marginController = TextEditingController();

  num lowerStockAlert = 5;
  String? expireDate;
  String? manufactureDate;

  late String productKey;

  void getProductKey(String code) async {
    // ignore: unused_local_variable
    List<ProductModel> productList = [];
    await FirebaseDatabase.instance.ref(await getUserID()).child('Products').orderByKey().get().then((value) {
      for (var element in value.children) {
        var data = jsonDecode(jsonEncode(element.value));
        if (data['productCode'].toString() == code) {
          productKey = element.key.toString();
        }
      }
    });
  }

  late ProductModel productModel;
  bool warehouseInitialized = false;

  // String purchasePrice=Product.productModel;
  // String salePrice=productModel.productSalePrice;
  // String dealerPrice=productModel.productDealerPrice;
  // String wholeSalePrice=productModel.productWholeSalePrice;

  Timer? _calculationTimer;
  final Duration _calculationDelay = const Duration(milliseconds: 800);
  String mrpText = '';
  String purchaseText = '';
  String wholesaleText = '';
  String dealerText = '';
  String excTaxAmount = '';
  String incTaxAmount = '';

  String _cleanNumberInput(String input) {
    return input.replaceAll(',', '').replaceAll(RegExp(r'[^\d.]'), '');
  }

  void calculatePurchaseAndMrp({String? from}) {
    double purchasePrice = double.tryParse(_cleanNumberInput(productPurchasePriceController.text)) ?? 0;
    double salePrice = double.tryParse(_cleanNumberInput(productSalePriceController.text)) ?? 0;
    double taxRate = selectedGroupTaxModel != null ? double.parse(selectedGroupTaxModel!.taxRate.toString()) : 0.0;

    if (from == 'mrp') {
      if (salePrice > 0 && purchasePrice > 0) {
        // Calculate profit margin based on the actual sale price (excluding tax for exclusive)
        double actualSalePrice = selectedTaxType == 'Exclusive' ? salePrice / (1 + (taxRate / 100)) : salePrice;

        double profitMargin = ((actualSalePrice - purchasePrice) / purchasePrice) * 100;
        marginController.text = profitMargin.toStringAsFixed(2);
        adjustSalesPrices();
      }
    } else if (from == 'margin') {
      if (purchasePrice > 0) {
        adjustSalesPrices();
      }
    } else if (from == 'purchase') {
      if (purchasePrice > 0) {
        adjustSalesPrices();
      }
    }
  }

  void adjustSalesPrices() {
    double purchasePrice = double.tryParse(productPurchasePriceController.text.replaceAll(',', '')) ?? 0;
    double margin = double.tryParse(marginController.text) ?? 0;
    double taxRate = selectedGroupTaxModel != null ? double.parse(selectedGroupTaxModel!.taxRate.toString()) : 0.0;

    if (purchasePrice <= 0) return;

    // Calculate base price without tax first
    double basePrice = purchasePrice + (purchasePrice * margin / 100);

    double taxAmount = basePrice * (taxRate / 100);

    if (selectedTaxType == 'Inclusive') {
      // For inclusive tax: Price includes tax
      double priceWithTax = basePrice;
      double priceWithoutTax = priceWithTax / (1 + (taxRate / 100));

      mrpText = priceWithTax.toStringAsFixed(2);
      incTaxAmount = priceWithTax.toStringAsFixed(2);
      excTaxAmount = priceWithoutTax.toStringAsFixed(2);

      productSalePriceController.text = mrpText;
    } else {
      // For exclusive tax: Price doesn't include tax, tax is added separately
      double priceWithoutTax = basePrice;
      double priceWithTax = basePrice + taxAmount;

      mrpText = priceWithTax.toStringAsFixed(2);
      incTaxAmount = priceWithTax.toStringAsFixed(2);
      excTaxAmount = priceWithoutTax.toStringAsFixed(2);

      // Update sale price controller with the total price (including tax)
      productSalePriceController.text = mrpText;
    }

    // Update wholesale and dealer prices to match MRP
    productWholesalePriceController.text = mrpText;
    productDealerPriceController.text = mrpText;

    // Update tax display fields
    incTaxController.text = incTaxAmount;
    excTaxController.text = excTaxAmount;

    setState(() {});
  }

  void scheduleCalculation({String? from}) {
    _calculationTimer?.cancel();
    _calculationTimer = Timer(_calculationDelay, () {
      calculatePurchaseAndMrp(from: from);
    });
  }

  @override
  void initState() {
    // Use delayed calculation instead of immediate listeners
    productPurchasePriceController.addListener(() {
      scheduleCalculation(from: 'purchase');
    });

    productSalePriceController.addListener(() {
      scheduleCalculation(from: 'mrp');
    });

    marginController.addListener(() {
      scheduleCalculation(from: 'margin');
    });

    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) adjustSalesPrices();
    });
    productModel = widget.productModel;
    productNameController.text = widget.productModel.productName;
    productSalePriceController.text = widget.productModel.productSalePrice;
    quantityController.text = widget.productModel.productStock;
    productPurchasePriceController.text = widget.productModel.productPurchasePrice;
    productDiscountPriceController.text = widget.productModel.productDiscount;
    productWholesalePriceController.text = widget.productModel.productWholeSalePrice;
    productDealerPriceController.text = widget.productModel.productDealerPrice;
    productManufacturerController.text = widget.productModel.productManufacturer;
    sizeController.text = widget.productModel.size;
    colorController.text = widget.productModel.color;
    weightController.text = widget.productModel.weight;
    capacityController.text = widget.productModel.capacity;
    // itemCategoryController.text=widget.productModel.productCategory;
    // unitNameController.text=widget.productModel.productUnit;
    // brandNameController.text=widget.productModel.brandName;
    selectedCategories = widget.productModel.productCategory;
    selectedUnit = widget.productModel.productUnit;
    selectedBrand = widget.productModel.brandName;
    // selectedWareHouse?.warehouseName=widget.productModel.warehouseName;
    typeController.text = widget.productModel.type;
    warrantyController.text = widget.productModel.warranty.getNumericOnly();
    getProductKey(widget.productModel.productCode);
    warehouseInitialized = false;
    if (!widget.productModel.warranty.isEmptyOrNull) {
      if (widget.productModel.warranty.contains('Month')) {
        selectedTime = 'Month';
      } else if (widget.productModel.warranty.contains('Year')) {
        selectedTime = 'Year';
      } else {
        selectedTime = 'Day';
      }
    }
    if (widget.productModel.expiringDate != null) {
      expireDateTextEditingController.text =
          DateFormat.yMMMd().format(DateTime.parse(widget.productModel.expiringDate!));
      expireDate = widget.productModel.expiringDate;
    }
    if (widget.productModel.manufacturingDate != null) {
      manufactureDateTextEditingController.text =
          DateFormat.yMMMd().format(DateTime.parse(widget.productModel.manufacturingDate!));
      manufactureDate = widget.productModel.manufacturingDate;
    }

    lowerStockAlert = widget.productModel.lowerStockAlert;

    productPicture = widget.productModel.productPicture;

    widget.productModel.serialNumber.isNotEmpty ? isSerialNumberTaken = true : isSerialNumberTaken = false;
    marginController.text = widget.productModel.margin.toString();
    incTaxController.text = widget.productModel.incTax.toString();
    excTaxController.text = widget.productModel.excTax.toString();
    selectedTaxType = widget.productModel.taxType;

    GroupTaxModel groupTaxModel = GroupTaxModel(
        name: widget.productModel.groupTaxName,
        taxRate: widget.productModel.groupTaxRate,
        id: '',
        subTaxes: widget.productModel.subTaxes);
    bool isInList = false;
    for (var element in widget.groupTaxModel) {
      if (element.name == groupTaxModel.name) {
        isInList = true;
        groupTaxModel = element;
        continue;
      }
    }
    if (isInList) {
      selectedGroupTaxModel = groupTaxModel;
    }

    super.initState();
    checkCurrentUserAndRestartApp();
  }

  ScrollController mainScroll = ScrollController();

  //___________________________________tax_dropdown________________________________
  DropdownButton<GroupTaxModel> getTax({required List<GroupTaxModel> list}) {
    return DropdownButton(
      hint: const Text('Select Tax'),
      items: list.map((e) {
        return DropdownMenuItem(
          value: e,
          child: Text(e.name),
        );
      }).toList(),
      value: selectedGroupTaxModel,
      onChanged: (value) {
        setState(() {
          selectedGroupTaxModel = value!;
        });
      },
    );
  }

  GroupTaxModel? selectedGroupTaxModel;

  //___________________________________tax_type____________________________________
  List<String> status = [
    'Inclusive',
    'Exclusive',
  ];

  String selectedTaxType = 'Exclusive';

  DropdownButton<String> getTaxType() {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (String des in status) {
      var item = DropdownMenuItem(
        value: des,
        child: Text(des),
      );
      dropDownItems.add(item);
    }
    return DropdownButton(
      hint: const Text('Select Tax type'),
      items: dropDownItems,
      value: selectedTaxType,
      onChanged: (value) {
        setState(() {
          selectedTaxType = value!;
          adjustSalesPrices();
        });
      },
    );
  }

  //___________________________________calculate_total_with_tax____________________
  double totalAmount = 0.0;

  void calculateTotal() {
    String saleAmountText = productPurchasePriceController.text.replaceAll(',', '');
    double saleAmount = double.tryParse(saleAmountText) ?? 0.0;
    if (selectedGroupTaxModel != null) {
      double taxRate = double.parse(selectedGroupTaxModel!.taxRate.toString());
      double totalAmount = calculateTotalAmount(saleAmount, taxRate);
      setState(() {
        totalAmountController.text = totalAmount.toStringAsFixed(2);
        this.totalAmount = totalAmount;
      });
    }
  }

  double calculateTotalAmount(double saleAmount, double taxRate) {
    double taxDecimal = taxRate / 100;
    double totalAmount = saleAmount + (saleAmount * taxDecimal);
    return totalAmount;
  }

  // void adjustSalesPrices() {
  //   // double taxAmount = double.tryParse(selectedGroupTaxModel?.taxRate.toString() ?? '') ?? 0.0;
  //   double margin = double.tryParse(marginController.text) ?? 0;
  //   double purchasePrice = double.tryParse(productPurchasePriceController.text) ?? 0;
  //   double salesPrice = 0;
  //   double excPrice = 0;
  //   double taxAmount =
  //       calculateAmountFromPercentage((selectedGroupTaxModel?.taxRate.toString() ?? '').toDouble(), purchasePrice);
  //
  //   if (selectedTaxType == 'Inclusive') {
  //     salesPrice = purchasePrice + calculateAmountFromPercentage(margin, purchasePrice);
  //     // salesPrice -= calculateAmountFromPercentage(double.parse(selectedGroupTaxModel!.taxRate.toString()), purchasePrice);
  //     productSalePriceController.text = salesPrice.toString();
  //     productDealerPriceController.text = salesPrice.toString();
  //     productWholesalePriceController.text = salesPrice.toString();
  //     incTaxController.text = purchasePrice.toString();
  //     excTaxController.text = salesPrice.toString();
  //   } else {
  //     salesPrice = purchasePrice + calculateAmountFromPercentage(margin, purchasePrice) + taxAmount;
  //     excPrice = purchasePrice + taxAmount;
  //     productSalePriceController.text = salesPrice.toString();
  //     productDealerPriceController.text = salesPrice.toString();
  //     productWholesalePriceController.text = salesPrice.toString();
  //     incTaxController.text = purchasePrice.toString();
  //     excTaxController.text = excPrice.toString();
  //   }
  //
  //   // Add margin to prices if margin is provided
  //
  //   // Update controllers with adjusted prices
  //   productSalePriceController.text = salesPrice.toStringAsFixed(2);
  //   productWholesalePriceController.text = salesPrice.toStringAsFixed(2);
  //   productDealerPriceController.text = salesPrice.toStringAsFixed(2);
  //   incTaxController.text = salesPrice.toStringAsFixed(2);
  //   excTaxController.text = excPrice.toStringAsFixed(2);
  // }

  // Function to calculate the amount from a given percentage
  double calculateAmountFromPercentage(double percentage, double price) {
    return price * (percentage / 100);
  }

  int i = 0;
  WareHouseModel? selectedWareHouse;
  DropdownButton<WareHouseModel> getName({required List<WareHouseModel> list}) {
    return DropdownButton(
      items: list.map((WareHouseModel warehouse) {
        return DropdownMenuItem<WareHouseModel>(
          value: warehouse,
          child: SizedBox(
            width: 110,
            child: Text(
              warehouse.warehouseName,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        );
      }).toList(),
      icon: const Icon(
        Icons.keyboard_arrow_down,
        color: kGreyTextColor,
      ),
      value: selectedWareHouse,
      onChanged: (WareHouseModel? value) {
        setState(() {
          selectedWareHouse = value;
        });
      },
    );
  }

  String? selectedBrand;
  String? selectedCategories;
  String? selectedUnit;

  @override
  Widget build(BuildContext context) {
    print('----------image is $image----------');
    print('----------Product image is $productPicture----------');
    final theme = Theme.of(context);
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: kDarkWhite,
      body: Consumer(
        builder: (context, ref, __) {
          final wareHouseList = ref.watch(warehouseProvider);
          final unitList = ref.watch(unitProvider);
          final brandList = ref.watch(brandProvider);
          final categoryList = ref.watch(categoryProvider);
          final groupTax = ref.watch(groupTaxProvider);
          return SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // const TopBar(),
                const SizedBox(height: 20.0),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 20.0),
                    Padding(
                      padding: const EdgeInsets.only(left: 10.0),
                      child: Text(
                        lang.S.of(context).addProduct,
                        style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                      ),
                    ),
                    ResponsiveGridRow(children: [
                      ResponsiveGridCol(
                          xs: 12,
                          md: screenWidth < 778 ? 12 : 8,
                          lg: screenWidth < 778 ? 12 : 8,
                          child: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Column(
                              children: [
                                Container(
                                  width: double.infinity,
                                  padding: const EdgeInsets.all(10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10.0),
                                    color: kWhite,
                                  ),
                                  child: Form(
                                    key: addProductFormKey,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const SizedBox(height: 10.0),

                                        ///________Name_And_Category_____________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Padding(
                                                padding: const EdgeInsets.all(10.0),
                                                child: TextFormField(
                                                  validator: (value) {
                                                    if (value.removeAllWhiteSpace().isEmptyOrNull) {
                                                      return 'Product name is required.';
                                                    } else if (widget.allProductsNameList
                                                            .contains(value.removeAllWhiteSpace().toLowerCase()) &&
                                                        widget.productModel.productName != value) {
                                                      return 'Product Name already exist.';
                                                    } else {
                                                      return null;
                                                    }
                                                  },
                                                  onSaved: (value) {
                                                    productNameController.text = value!;
                                                  },
                                                  showCursor: true,
                                                  controller: productNameController,
                                                  cursorColor: kTitleColor,
                                                  decoration: InputDecoration(
                                                    labelText: lang.S.of(context).productNam,
                                                    hintText: lang.S.of(context).enterProductName,
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: categoryList.when(
                                              data: (category) {
                                                List<String> editNameList = [];
                                                List<String> categoryName = [];

                                                for (var element in category) {
                                                  categoryName.add(element.categoryName);
                                                  editNameList
                                                      .add(element.categoryName.toLowerCase().removeAllWhiteSpace());
                                                }

                                                // Check if the selected category exists in the current list
                                                final bool categoryExists = categoryName.contains(selectedCategories);

                                                return Padding(
                                                  padding: const EdgeInsets.all(10.0),
                                                  child: SizedBox(
                                                    height: 48,
                                                    child: FormField(
                                                      builder: (FormFieldState<dynamic> field) {
                                                        return InputDecorator(
                                                          decoration: InputDecoration(
                                                            suffixIcon: GestureDetector(
                                                              onTap: () async {
                                                                await addCategoryShowPopUp(
                                                                    ref: ref,
                                                                    categoryNameList: editNameList,
                                                                    addProductContext: context);
                                                              },
                                                              child: Container(
                                                                height: 48,
                                                                width: 48,
                                                                alignment: Alignment.center,
                                                                decoration: const BoxDecoration(
                                                                  color: kMainColor100,
                                                                  borderRadius: BorderRadius.only(
                                                                    topRight: Radius.circular(8),
                                                                    bottomRight: Radius.circular(8),
                                                                  ),
                                                                ),
                                                                child: const Icon(FeatherIcons.plusSquare,
                                                                    color: kMainColor),
                                                              ),
                                                            ),
                                                            contentPadding: const EdgeInsets.all(8.0),
                                                            floatingLabelBehavior: FloatingLabelBehavior.always,
                                                            labelText: lang.S.of(context).category,
                                                          ),
                                                          child: Theme(
                                                            data: ThemeData(
                                                                highlightColor: dropdownItemColor,
                                                                focusColor: dropdownItemColor,
                                                                hoverColor: dropdownItemColor),
                                                            child: DropdownButtonHideUnderline(
                                                              child: DropdownButton<String>(
                                                                icon: const Icon(
                                                                  Icons.keyboard_arrow_down,
                                                                  color: kGreyTextColor,
                                                                ),
                                                                hint: Text(
                                                                  'Select Category',
                                                                  maxLines: 1,
                                                                  overflow: TextOverflow.ellipsis,
                                                                ),
                                                                onChanged: (String? value) {
                                                                  setState(() {
                                                                    selectedCategories = value!;
                                                                    for (var element in category) {
                                                                      if (element.categoryName == selectedCategories) {
                                                                        isSizedBoxShow = element.size;
                                                                        isColoredBoxShow = element.color;
                                                                        isWeightsBoxShow = element.weight;
                                                                        isCapacityBoxShow = element.capacity;
                                                                        isTypeBoxShow = element.type;
                                                                        isWarrantyBoxShow = element.warranty;
                                                                      }
                                                                    }
                                                                  });
                                                                },
                                                                value: categoryExists ? selectedCategories : null,
                                                                items: [
                                                                  // Add the existing category as a disabled item if it doesn't exist in the current list
                                                                  if (!categoryExists && selectedCategories != null)
                                                                    DropdownMenuItem<String>(
                                                                      value: selectedCategories,
                                                                      enabled: false,
                                                                      child: Text(
                                                                        '$selectedCategories (Not in list)',
                                                                        style: TextStyle(
                                                                            color: Colors.grey,
                                                                            fontStyle: FontStyle.italic),
                                                                      ),
                                                                    ),
                                                                  ...categoryName.map((String items) {
                                                                    return DropdownMenuItem(
                                                                      value: items,
                                                                      child: FittedBox(
                                                                        fit: BoxFit.scaleDown,
                                                                        child: Text(items),
                                                                      ),
                                                                    );
                                                                  }).toList(),
                                                                ],
                                                              ),
                                                            ),
                                                          ),
                                                        );
                                                      },
                                                    ),
                                                  ),
                                                );
                                              },
                                              error: (e, stack) {
                                                return Center(
                                                  child: Text(
                                                    e.toString(),
                                                  ),
                                                );
                                              },
                                              loading: () {
                                                return const Center(
                                                  child: CircularProgressIndicator(),
                                                );
                                              },
                                            ),
                                          )
                                        ]),

                                        ///________Size_&_Color____________________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: widget.productModel.color.isNotEmpty ? 6 : 12,
                                              lg: widget.productModel.color.isNotEmpty ? 6 : 12,
                                              child: Visibility(
                                                visible: widget.productModel.size.isNotEmpty,
                                                child: Padding(
                                                  padding: const EdgeInsets.all(10.0),
                                                  child: TextFormField(
                                                    validator: (value) {
                                                      return null;
                                                    },
                                                    showCursor: true,
                                                    controller: sizeController,
                                                    cursorColor: kTitleColor,
                                                    keyboardType: TextInputType.name,
                                                    decoration: InputDecoration(
                                                      labelText: lang.S.of(context).productSize,
                                                      hintText: lang.S.of(context).enterProductSize,
                                                    ),
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: widget.productModel.size.isNotEmpty ? 6 : 12,
                                              lg: widget.productModel.size.isNotEmpty ? 6 : 12,
                                              child: Visibility(
                                                visible: widget.productModel.color.isNotEmpty,
                                                child: Padding(
                                                  padding: const EdgeInsets.all(10.0),
                                                  child: TextFormField(
                                                    validator: (value) {
                                                      return null;
                                                    },
                                                    showCursor: true,
                                                    controller: colorController,
                                                    cursorColor: kTitleColor,
                                                    keyboardType: TextInputType.name,
                                                    decoration: InputDecoration(
                                                      labelText: lang.S.of(context).productColor,
                                                      hintText: lang.S.of(context).enterProductColor,
                                                    ),
                                                  ),
                                                ),
                                              ))
                                        ]),

                                        ///_____________Weight_&_Capacity___________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: widget.productModel.capacity.isNotEmpty ? 6 : 12,
                                              lg: widget.productModel.capacity.isNotEmpty ? 6 : 12,
                                              child: Visibility(
                                                visible: widget.productModel.weight.isNotEmpty,
                                                child: Padding(
                                                  padding: const EdgeInsets.all(10.0),
                                                  child: TextFormField(
                                                    validator: (value) {
                                                      return null;
                                                    },
                                                    showCursor: true,
                                                    controller: weightController,
                                                    cursorColor: kTitleColor,
                                                    keyboardType: TextInputType.name,
                                                    decoration: InputDecoration(
                                                      labelText: lang.S.of(context).productWeight,
                                                      hintText: lang.S.of(context).enterProductWeight,
                                                    ),
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: widget.productModel.weight.isNotEmpty ? 6 : 12,
                                              lg: widget.productModel.weight.isNotEmpty ? 6 : 12,
                                              child: Visibility(
                                                visible: widget.productModel.capacity.isNotEmpty,
                                                child: Padding(
                                                  padding: const EdgeInsets.all(10),
                                                  child: TextFormField(
                                                    validator: (value) {
                                                      return null;
                                                    },
                                                    showCursor: true,
                                                    controller: capacityController,
                                                    cursorColor: kTitleColor,
                                                    keyboardType: TextInputType.name,
                                                    decoration: InputDecoration(
                                                      labelText: lang.S.of(context).productcapacity,
                                                      hintText: lang.S.of(context).enterProductCapacity,
                                                    ),
                                                  ),
                                                ),
                                              ))
                                        ]),

                                        ///_____________Type_&_Warranty___________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: widget.productModel.warranty.isNotEmpty ? 6 : 12,
                                              lg: widget.productModel.warranty.isNotEmpty ? 6 : 12,
                                              child: Visibility(
                                                visible: widget.productModel.type.isNotEmpty,
                                                child: Padding(
                                                  padding: const EdgeInsets.all(10),
                                                  child: TextFormField(
                                                    validator: (value) {
                                                      return null;
                                                    },
                                                    showCursor: true,
                                                    controller: typeController,
                                                    cursorColor: kTitleColor,
                                                    keyboardType: TextInputType.name,
                                                    decoration: InputDecoration(
                                                      labelText: lang.S.of(context).productType,
                                                      hintText: lang.S.of(context).enterProductType,
                                                    ),
                                                  ),
                                                ),
                                              )),
                                        ]),

                                        ///_______brand_&_ProductCode________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: brandList.when(data: (brand) {
                                                List<String> editBrandList = [];
                                                List<String> brandName = [];

                                                for (var element in brand) {
                                                  brandName.add(element.brandName);
                                                  editBrandList
                                                      .add(element.brandName.toLowerCase().removeAllWhiteSpace());
                                                }

                                                // Check if the selected brand exists in the current list
                                                final bool brandExists = brandName.contains(selectedBrand);

                                                return SizedBox(
                                                  height: 48,
                                                  child: FormField(
                                                    builder: (FormFieldState<dynamic> field) {
                                                      return InputDecorator(
                                                        decoration: InputDecoration(
                                                          suffixIcon: Container(
                                                            height: 48,
                                                            width: 48,
                                                            decoration: const BoxDecoration(
                                                              color: kMainColor100,
                                                              borderRadius: BorderRadius.only(
                                                                bottomRight: Radius.circular(8),
                                                                topRight: Radius.circular(8),
                                                              ),
                                                            ),
                                                            child:
                                                                const Icon(FeatherIcons.plusSquare, color: kMainColor)
                                                                    .onTap(() => showBrandPopUp(
                                                                        ref: ref,
                                                                        brandNameList: editBrandList,
                                                                        addProductsContext: context)),
                                                          ),
                                                          contentPadding: const EdgeInsets.all(8.0),
                                                          labelText: lang.S.of(context).brand,
                                                        ),
                                                        child: Theme(
                                                          data: ThemeData(
                                                              highlightColor: dropdownItemColor,
                                                              focusColor: dropdownItemColor,
                                                              hoverColor: dropdownItemColor),
                                                          child: DropdownButtonHideUnderline(
                                                            child: DropdownButton<String>(
                                                              isExpanded: true,
                                                              onChanged: (String? value) {
                                                                setState(() {
                                                                  selectedBrand = value!;
                                                                });
                                                              },
                                                              hint: Text(
                                                                lang.S.of(context).selectProductBrand,
                                                                maxLines: 1,
                                                                overflow: TextOverflow.ellipsis,
                                                              ),
                                                              value: brandExists ? selectedBrand : null,
                                                              items: [
                                                                // Add the existing brand as a disabled item if it doesn't exist in the current list
                                                                if (!brandExists && selectedBrand != null)
                                                                  DropdownMenuItem<String>(
                                                                    value: selectedBrand,
                                                                    enabled: false,
                                                                    child: Text(
                                                                      '$selectedBrand (Not in list)',
                                                                      style: TextStyle(
                                                                          color: Colors.grey,
                                                                          fontStyle: FontStyle.italic),
                                                                    ),
                                                                  ),
                                                                ...brandName.map((String items) {
                                                                  return DropdownMenuItem(
                                                                    value: items,
                                                                    child: FittedBox(
                                                                        fit: BoxFit.scaleDown, child: Text(items)),
                                                                  );
                                                                }).toList(),
                                                              ],
                                                            ),
                                                          ),
                                                        ),
                                                      );
                                                    },
                                                  ),
                                                );
                                              }, error: (e, stack) {
                                                return Center(
                                                  child: Text(e.toString()),
                                                );
                                              }, loading: () {
                                                return const Center(
                                                  child: CircularProgressIndicator(),
                                                );
                                              }),
                                            ),
                                          ),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Padding(
                                                padding: const EdgeInsets.all(10.0),
                                                child: TextFormField(
                                                  initialValue: widget.productModel.productCode,
                                                  cursorColor: kTitleColor,
                                                  decoration: InputDecoration(
                                                    labelText: lang.S.of(context).productCod,
                                                    hintText: lang.S.of(context).enterProductCode,
                                                    suffixIcon: const Icon(
                                                      Icons.scanner,
                                                      color: kTitleColor,
                                                    ),
                                                  ),
                                                ),
                                              )),
                                        ]),

                                        ///______quantity_&_Unit______________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Padding(
                                                padding: const EdgeInsets.all(10.0),
                                                child: TextFormField(
                                                  controller: quantityController,
                                                  onSaved: (value) {
                                                    quantityController.text = value!;
                                                  },
                                                  cursorColor: kTitleColor,
                                                  decoration: InputDecoration(
                                                    labelText: lang.S.of(context).Quantity,
                                                    hintText: lang.S.of(context).enterProductQuantity,
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: unitList.when(
                                              data: (unit) {
                                                List<String> editBrandList = [];
                                                List<String> brandName = [];

                                                for (var element in unit) {
                                                  brandName.add(element.unitName);
                                                  editBrandList
                                                      .add(element.unitName.toLowerCase().removeAllWhiteSpace());
                                                }

                                                // Check if the selected unit exists in the current list
                                                final bool unitExists = brandName.contains(selectedUnit);

                                                return Padding(
                                                  padding: const EdgeInsets.all(10.0),
                                                  child: SizedBox(
                                                    height: 48,
                                                    child: FormField(
                                                      builder: (FormFieldState<dynamic> field) {
                                                        return InputDecorator(
                                                          decoration: InputDecoration(
                                                            hint: Text('Select a unit'),
                                                            suffixIcon: Container(
                                                              height: 48,
                                                              width: 48,
                                                              alignment: Alignment.center,
                                                              decoration: const BoxDecoration(
                                                                color: kMainColor100,
                                                                borderRadius: BorderRadius.only(
                                                                  bottomRight: Radius.circular(8),
                                                                  topRight: Radius.circular(8),
                                                                ),
                                                              ),
                                                              child:
                                                                  const Icon(FeatherIcons.plusSquare, color: kMainColor)
                                                                      .onTap(() => showUnitPopUp(
                                                                          ref: ref,
                                                                          unitNameList: editBrandList,
                                                                          addProductsContext: context)),
                                                            ),
                                                            contentPadding:
                                                                const EdgeInsets.only(left: 8.0, top: 8, bottom: 8),
                                                            floatingLabelBehavior: FloatingLabelBehavior.always,
                                                            labelText: lang.S.of(context).productUnit,
                                                          ),
                                                          child: Theme(
                                                            data: ThemeData(
                                                              highlightColor: dropdownItemColor,
                                                              focusColor: dropdownItemColor,
                                                              hoverColor: dropdownItemColor,
                                                            ),
                                                            child: DropdownButtonHideUnderline(
                                                              child: DropdownButton<String>(
                                                                hint: Text(
                                                                  'Select a unit',
                                                                  style: theme.textTheme.titleMedium?.copyWith(
                                                                    color: kNeutral700,
                                                                  ),
                                                                ),
                                                                isExpanded: true,
                                                                icon: const Icon(
                                                                  Icons.keyboard_arrow_down,
                                                                  color: kGreyTextColor,
                                                                ),
                                                                onChanged: (String? value) {
                                                                  setState(() {
                                                                    selectedUnit = value!;
                                                                  });
                                                                },
                                                                value: unitExists ? selectedUnit : null,
                                                                items: [
                                                                  // Add the existing unit as a disabled item if it doesn't exist in the current list
                                                                  if (!unitExists && selectedUnit != null)
                                                                    DropdownMenuItem<String>(
                                                                      value: selectedUnit,
                                                                      enabled: false,
                                                                      child: Text(
                                                                        '$selectedUnit (Not in list)',
                                                                        style: TextStyle(
                                                                            color: Colors.grey,
                                                                            fontStyle: FontStyle.italic),
                                                                      ),
                                                                    ),
                                                                  ...brandName
                                                                      .toSet() // Remove duplicates
                                                                      .map((String items) {
                                                                    return DropdownMenuItem(
                                                                      value: items,
                                                                      child: FittedBox(
                                                                        fit: BoxFit.scaleDown,
                                                                        child: Text(
                                                                          items,
                                                                          style: kTextStyle.copyWith(
                                                                              color: kTitleColor,
                                                                              fontWeight: FontWeight.normal),
                                                                        ),
                                                                      ),
                                                                    );
                                                                  }).toList(),
                                                                ],
                                                              ),
                                                            ),
                                                          ),
                                                        );
                                                      },
                                                    ),
                                                  ),
                                                );
                                              },
                                              error: (e, stack) {
                                                return Center(child: Text(e.toString()));
                                              },
                                              loading: () {
                                                return const Center(child: CircularProgressIndicator());
                                              },
                                            ),
                                          )
                                        ]),
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: TextFormField(
                                                validator: (value) {
                                                  return null;
                                                },
                                                onSaved: (value) {
                                                  productManufacturerController.text = value!;
                                                },
                                                controller: productManufacturerController,
                                                showCursor: true,
                                                cursorColor: kTitleColor,
                                                decoration: InputDecoration(
                                                  labelText: lang.S.of(context).manufacturer,
                                                  hintText: lang.S.of(context).enterManufacturerName,
                                                ),
                                              ),
                                            ),
                                          ),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: wareHouseList.when(
                                                data: (warehouse) {
                                                  // Set the initial selected warehouse based on the product's warehouse
                                                  if (!warehouseInitialized && warehouse.isNotEmpty) {
                                                    WidgetsBinding.instance.addPostFrameCallback((_) {
                                                      setState(() {
                                                        // Try to find the warehouse that matches the product's warehouse
                                                        selectedWareHouse = warehouse.firstWhere(
                                                          (warehouse) =>
                                                              warehouse.warehouseName ==
                                                              widget.productModel.warehouseName,
                                                          orElse: () => warehouse.first,
                                                        );
                                                        warehouseInitialized = true;
                                                      });
                                                    });
                                                  }

                                                  return SizedBox(
                                                    height: 48,
                                                    child: FormField(
                                                      builder: (FormFieldState<dynamic> field) {
                                                        return InputDecorator(
                                                          decoration: const InputDecoration(
                                                              contentPadding: EdgeInsets.all(8.0),
                                                              floatingLabelBehavior: FloatingLabelBehavior.always,
                                                              labelText: 'Warehouse'),
                                                          child: Theme(
                                                            data: ThemeData(
                                                                highlightColor: dropdownItemColor,
                                                                focusColor: dropdownItemColor,
                                                                hoverColor: dropdownItemColor),
                                                            child: DropdownButtonHideUnderline(
                                                              child: DropdownButton<WareHouseModel>(
                                                                isExpanded: true,
                                                                icon: const Icon(
                                                                  Icons.keyboard_arrow_down,
                                                                  color: kGreyTextColor,
                                                                ),
                                                                hint: Text(
                                                                  'Select Warehouse',
                                                                  style: theme.textTheme.titleMedium?.copyWith(
                                                                    color: kNeutral700,
                                                                  ),
                                                                ),
                                                                value: selectedWareHouse,
                                                                onChanged: (WareHouseModel? value) {
                                                                  setState(() {
                                                                    selectedWareHouse = value;
                                                                  });
                                                                },
                                                                items: warehouse.map((WareHouseModel warehouse) {
                                                                  return DropdownMenuItem<WareHouseModel>(
                                                                    value: warehouse,
                                                                    child: Text(
                                                                      warehouse.warehouseName,
                                                                      overflow: TextOverflow.ellipsis,
                                                                      style: kTextStyle.copyWith(
                                                                          color: kTitleColor,
                                                                          fontWeight: FontWeight.normal),
                                                                    ),
                                                                  );
                                                                }).toList(),
                                                              ),
                                                            ),
                                                          ),
                                                        );
                                                      },
                                                    ),
                                                  );
                                                },
                                                error: (e, stack) {
                                                  return Center(
                                                    child: Text(
                                                      e.toString(),
                                                    ),
                                                  );
                                                },
                                                loading: () {
                                                  return const Center(
                                                    child: CircularProgressIndicator(),
                                                  );
                                                },
                                              ),
                                            ),
                                          )
                                        ]),

                                        ///______________ExpireDate______________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Padding(
                                                padding: const EdgeInsets.all(10.0),
                                                child: TextFormField(
                                                  keyboardType: TextInputType.name,
                                                  readOnly: true,
                                                  validator: (value) {
                                                    return null;
                                                  },
                                                  controller: manufactureDateTextEditingController,
                                                  decoration: InputDecoration(
                                                    floatingLabelBehavior: FloatingLabelBehavior.always,
                                                    labelText: "Manufacture Date",
                                                    hintText: 'Enter Date',
                                                    suffixIcon: IconButton(
                                                      onPressed: () async {
                                                        final DateTime? picked = await showDatePicker(
                                                          // initialDate: DateTime.now(),
                                                          firstDate: DateTime(2015, 8),
                                                          lastDate: DateTime(2101),
                                                          context: context,
                                                        );
                                                        setState(() {
                                                          picked != null
                                                              ? manufactureDateTextEditingController.text =
                                                                  DateFormat.yMMMd().format(picked)
                                                              : null;
                                                          picked != null ? manufactureDate = picked.toString() : null;
                                                        });
                                                      },
                                                      icon: const Icon(IconlyLight.calendar),
                                                    ),
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Padding(
                                                padding: const EdgeInsets.all(10.0),
                                                child: TextFormField(
                                                  keyboardType: TextInputType.name,
                                                  readOnly: true,
                                                  validator: (value) {
                                                    return null;
                                                  },
                                                  controller: expireDateTextEditingController,
                                                  decoration: InputDecoration(
                                                    floatingLabelBehavior: FloatingLabelBehavior.always,
                                                    labelText: 'Expire Date',
                                                    hintText: 'Enter Date',
                                                    suffixIcon: IconButton(
                                                      onPressed: () async {
                                                        final DateTime? picked = await showDatePicker(
                                                          // initialDate: DateTime.now(),
                                                          firstDate: DateTime(2015, 8),
                                                          lastDate: DateTime(2101),
                                                          context: context,
                                                        );
                                                        setState(() {
                                                          picked != null
                                                              ? expireDateTextEditingController.text =
                                                                  DateFormat.yMMMd().format(picked)
                                                              : null;
                                                          picked != null ? expireDate = picked.toString() : null;
                                                        });
                                                      },
                                                      icon: const Icon(IconlyLight.calendar),
                                                    ),
                                                  ),
                                                ),
                                              )),
                                        ]),

                                        ///_______Lower_stock___________________________
                                        Padding(
                                          padding: const EdgeInsets.all(10.0),
                                          child: TextFormField(
                                            initialValue: lowerStockAlert.toString(),
                                            onSaved: (value) {
                                              lowerStockAlert = int.tryParse(value ?? '') ?? 5;
                                            },
                                            decoration: kInputDecoration.copyWith(
                                              floatingLabelBehavior: FloatingLabelBehavior.always,
                                              labelText: 'Low Stock Alert',
                                              hintText: 'Enter Low Stock Alert Quantity',
                                              border: const OutlineInputBorder(),
                                            ),
                                            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                                          ),
                                        ),
                                        // const SizedBox(height: 20.0),
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  height: 20,
                                ),
                                //-------------serial number----------------
                                Container(
                                  padding: const EdgeInsets.all(10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10.0),
                                    color: kWhite,
                                  ),
                                  child: Column(
                                    children: [
                                      ///_________product_serial____________________________________________
                                      Row(
                                        children: [
                                          Theme(
                                            data: ThemeData(
                                                checkboxTheme: const CheckboxThemeData(
                                                    side: BorderSide(
                                              color: kNeutral500,
                                            ))),
                                            child: Checkbox(
                                                value: isSerialNumberTaken,
                                                onChanged: (value) {
                                                  setState(() {
                                                    isSerialNumberTaken = value!;
                                                  });
                                                }),
                                          ),
                                          Flexible(
                                            child: Text.rich(TextSpan(
                                                text: 'Do you want to add a ',
                                                style: theme.textTheme.bodyLarge,
                                                children: [
                                                  TextSpan(
                                                      text: 'serial number?',
                                                      style: theme.textTheme.titleMedium?.copyWith(
                                                        color: kMainColor,
                                                      ))
                                                ])),
                                          ),
                                        ],
                                      ),
                                      ResponsiveGridRow(children: [
                                        ResponsiveGridCol(
                                          xs: 12,
                                          md: 9,
                                          lg: 9,
                                          child: Visibility(
                                            visible: isSerialNumberTaken,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: TextFormField(
                                                validator: (value) {
                                                  return null;
                                                },
                                                controller: productSerialNumberController,
                                                showCursor: true,
                                                cursorColor: kTitleColor,
                                                onFieldSubmitted: (value) {
                                                  if (isSerialNumberUnique(
                                                      allList: widget.productModel.serialNumber, newSerial: value)) {
                                                    setState(() {
                                                      widget.productModel.serialNumber.add(value);
                                                    });
                                                    productSerialNumberController.clear();
                                                  } else {
                                                    EasyLoading.showError('Serial number already added!');
                                                  }
                                                },
                                                keyboardType: TextInputType.name,
                                                decoration: InputDecoration(
                                                  labelText: lang.S.of(context).serialNumber,
                                                  hintText: lang.S.of(context).enterSerialNumber,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                        ResponsiveGridCol(
                                          xs: 4,
                                          md: 3,
                                          lg: 3,
                                          child: Visibility(
                                            visible: isSerialNumberTaken,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: ElevatedButton(
                                                onPressed: () {
                                                  if (productSerialNumberController.text.isEmpty ||
                                                      productSerialNumberController.text.trim().isEmpty) {
                                                    EasyLoading.showError('Please enter a serial number!');
                                                    return;
                                                  }

                                                  if (isSerialNumberUnique(
                                                      allList: widget.productModel.serialNumber,
                                                      newSerial: productSerialNumberController.text)) {
                                                    setState(() {
                                                      widget.productModel.serialNumber
                                                          .add(productSerialNumberController.text);
                                                    });
                                                    productSerialNumberController.clear();
                                                  } else {
                                                    EasyLoading.showError('Serial number already added!');
                                                  }
                                                },
                                                child: Text(
                                                  lang.S.of(context).add,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                        ResponsiveGridCol(
                                          xs: 12,
                                          md: 12,
                                          lg: 12,
                                          child: Visibility(
                                            visible: isSerialNumberTaken,
                                            child: Padding(
                                              padding: const EdgeInsets.all(10.0),
                                              child: Container(
                                                decoration: BoxDecoration(
                                                  border: Border.all(width: 1, color: kNeutral400),
                                                  borderRadius: const BorderRadius.all(Radius.circular(8)),
                                                ),
                                                child: GridView.builder(
                                                  shrinkWrap: true,
                                                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                                    crossAxisCount: screenWidth < 770 ? 2 : 4,
                                                    childAspectRatio: 3.5,
                                                    crossAxisSpacing: .5,
                                                    mainAxisSpacing: 0.5,
                                                  ),
                                                  physics: NeverScrollableScrollPhysics(),
                                                  itemCount: productModel.serialNumber.length,
                                                  itemBuilder: (BuildContext context, int index) {
                                                    if (productModel.serialNumber.isNotEmpty) {
                                                      return Padding(
                                                        padding: const EdgeInsets.all(5.0),
                                                        child: Container(
                                                          padding: const EdgeInsets.all(8),
                                                          color: kNeutral100,
                                                          height: 80,
                                                          child: Row(
                                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                            children: [
                                                              SizedBox(
                                                                width: 100,
                                                                height: 40,
                                                                child: Text(
                                                                  productModel.serialNumber[index],
                                                                  maxLines: 1,
                                                                  overflow: TextOverflow.ellipsis,
                                                                ),
                                                              ),
                                                              GestureDetector(
                                                                onTap: () {
                                                                  setState(() {
                                                                    productModel.serialNumber.removeAt(index);
                                                                  });
                                                                },
                                                                child: const Icon(
                                                                  Icons.cancel,
                                                                  color: Colors.red,
                                                                  size: 15,
                                                                ),
                                                              ),
                                                            ],
                                                          ),
                                                        ),
                                                      );
                                                    } else {
                                                      return const Text('No Serial Number Found');
                                                    }
                                                  },
                                                ),
                                              ),
                                            ),
                                          ),
                                        )
                                      ]),
                                    ],
                                  ),
                                ),
                                const SizedBox(
                                  height: 20,
                                ),
                                Container(
                                  padding: const EdgeInsets.all(10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10.0),
                                    color: kWhite,
                                  ),
                                  child: Column(children: [
                                    ///________Tax && Type____________________________________________________
                                    ResponsiveGridRow(children: [
                                      ResponsiveGridCol(
                                          lg: 6,
                                          md: 6,
                                          xs: 12,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: FormField(
                                              builder: (FormFieldState<dynamic> field) {
                                                return InputDecorator(
                                                  decoration: const InputDecoration(
                                                    labelText: 'Applicable Tax',
                                                  ),
                                                  child: DropdownButtonHideUnderline(
                                                    child: DropdownButton<GroupTaxModel>(
                                                      isExpanded: true,
                                                      icon: const Icon(
                                                        Icons.keyboard_arrow_down,
                                                        color: kGreyTextColor,
                                                      ),
                                                      hint: Text(
                                                        'Select Tax',
                                                        maxLines: 1,
                                                        overflow: TextOverflow.ellipsis,
                                                      ),
                                                      items: widget.groupTaxModel.map((e) {
                                                        return DropdownMenuItem<GroupTaxModel>(
                                                          value: e,
                                                          child: Text(e.name),
                                                        );
                                                      }).toList(),
                                                      value: selectedGroupTaxModel,
                                                      onChanged: (value) {
                                                        setState(() {
                                                          selectedGroupTaxModel = value;
                                                          calculateTotal();
                                                          adjustSalesPrices(); // Update total amount when tax changes
                                                        });
                                                      },
                                                    ),
                                                  ),
                                                );
                                              },
                                            ),
                                          )),
                                      ResponsiveGridCol(
                                          lg: 6,
                                          md: 6,
                                          xs: 12,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: SizedBox(
                                              height: 48,
                                              child: FormField(
                                                builder: (FormFieldState<dynamic> field) {
                                                  return InputDecorator(
                                                    decoration: const InputDecoration(
                                                        contentPadding: EdgeInsets.all(8.0), labelText: 'Tax Type'),
                                                    child: DropdownButtonHideUnderline(
                                                      child: getTaxType(),
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                          ))
                                    ]),

                                    ///________Margin____________________________________________________
                                    ResponsiveGridRow(children: [
                                      ResponsiveGridCol(
                                          xs: 12,
                                          md: 6,
                                          lg: 6,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              controller: marginController,
                                              keyboardType: TextInputType.numberWithOptions(decimal: true),
                                              onEditingComplete: () {
                                                final value = double.tryParse(productPurchasePriceController.text) ?? 0;
                                                productPurchasePriceController.text =
                                                    value == 0 ? '' : value.toStringAsFixed(2);
                                                calculatePurchaseAndMrp(from: 'margin');
                                              },
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: kInputDecoration.copyWith(
                                                labelText: 'Margin %',
                                                hintText: '0',
                                                labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                                floatingLabelBehavior: FloatingLabelBehavior.always,
                                              ),
                                            ),
                                          )),
                                      ResponsiveGridCol(
                                        xs: 12,
                                        md: selectedTaxType == 'Inclusive' ? 6 : 0,
                                        lg: selectedTaxType == 'Inclusive' ? 6 : 0,
                                        child: Visibility(
                                          visible: selectedTaxType == 'Inclusive',
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              readOnly: true,
                                              controller: incTaxController,
                                              keyboardType: TextInputType.number,
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: kInputDecoration.copyWith(
                                                labelText: 'Inc. tax:',
                                                hintText: '0',
                                                labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                                floatingLabelBehavior: FloatingLabelBehavior.always,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      ResponsiveGridCol(
                                        xs: 12,
                                        md: selectedTaxType == 'Exclusive' ? 6 : 0,
                                        lg: selectedTaxType == 'Exclusive' ? 6 : 0,
                                        child: Visibility(
                                          visible: selectedTaxType == 'Exclusive',
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              readOnly: true,
                                              controller: excTaxController,
                                              keyboardType: TextInputType.number,
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: kInputDecoration.copyWith(
                                                labelText: 'Exc. tax:',
                                                hintText: '0',
                                                labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                                floatingLabelBehavior: FloatingLabelBehavior.always,
                                              ),
                                            ),
                                          ),
                                        ),
                                      )
                                    ]),

                                    ///__________Sale_Price_&_Purchase_Price_______________________________
                                    ResponsiveGridRow(children: [
                                      ResponsiveGridCol(
                                          lg: 6,
                                          md: 6,
                                          xs: 12,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              controller: productPurchasePriceController,
                                              keyboardType: TextInputType.numberWithOptions(decimal: true),
                                              onSaved: (value) {
                                                purchaseText = value?.replaceAll(',', '') ?? '0';
                                              },
                                              onEditingComplete: () {
                                                final value = double.tryParse(productPurchasePriceController.text) ?? 0;
                                                productPurchasePriceController.text =
                                                    value == 0 ? '' : value.toStringAsFixed(2);
                                                calculatePurchaseAndMrp(from: 'purchase');
                                              },
                                              onChanged: (value) {
                                                purchaseText = value.replaceAll(',', '');
                                                adjustSalesPrices();
                                                var formattedText = myFormat.format(int.parse(purchaseText));
                                                productPurchasePriceController.value =
                                                    productPurchasePriceController.value.copyWith(
                                                  text: formattedText,
                                                  selection: TextSelection.collapsed(offset: formattedText.length),
                                                );
                                              },
                                              validator: (value) {
                                                if (value.isEmptyOrNull) {
                                                  //return 'Purchase Price is required';
                                                  return "Purchase price is required";
                                                }
                                                return null;
                                              },
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: kInputDecoration.copyWith(
                                                errorBorder:
                                                    const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                                labelText: lang.S.of(context).purchasePrice,
                                                labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                                hintText: lang.S.of(context).enterPurchasePrice,
                                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                              ),
                                            ),
                                          )),
                                      ResponsiveGridCol(
                                          lg: 6,
                                          md: 6,
                                          xs: 12,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              controller: productSalePriceController,
                                              keyboardType: TextInputType.numberWithOptions(decimal: true),
                                              onSaved: (value) {
                                                mrpText = value?.replaceAll(',', '') ?? '0';
                                              },
                                              onEditingComplete: () {
                                                final value = double.tryParse(productSalePriceController.text) ?? 0;
                                                productSalePriceController.text =
                                                    value == 0 ? '' : value.toStringAsFixed(2);
                                                calculatePurchaseAndMrp(from: 'mrp');
                                              },
                                              validator: (value) {
                                                if (value.isEmptyOrNull) {
                                                  //return 'MRP is required';
                                                  return 'Sale Price is Required';
                                                }
                                                return null;
                                              },
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: kInputDecoration.copyWith(
                                                errorBorder:
                                                    const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                                labelText: lang.S.of(context).salePrices,
                                                labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                                hintText: lang.S.of(context).enterSalePrice,
                                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                              ),
                                            ),
                                          ))
                                    ]),

                                    ///__________Dealer &_Wholesele_Price______________________________________
                                    ResponsiveGridRow(children: [
                                      ResponsiveGridCol(
                                          xs: 12,
                                          md: 6,
                                          lg: 6,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              validator: (value) {
                                                if (double.tryParse(value!) == null && !value.isEmptyOrNull) {
                                                  return 'Enter price in number.';
                                                } else {
                                                  return null;
                                                }
                                              },
                                              onSaved: (value) {
                                                productDealerPriceController.text = value!;
                                              },
                                              controller: productDealerPriceController,
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: InputDecoration(
                                                labelText: lang.S.of(context).dealerPrice,
                                                hintText: lang.S.of(context).enterDealePrice,
                                              ),
                                            ),
                                          )),
                                      ResponsiveGridCol(
                                          xs: 12,
                                          md: 6,
                                          lg: 6,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10.0),
                                            child: TextFormField(
                                              validator: (value) {
                                                if (double.tryParse(value!) == null && !value.isEmptyOrNull) {
                                                  return 'Enter price in number.';
                                                } else {
                                                  return null;
                                                }
                                              },
                                              onSaved: (value) {
                                                productWholesalePriceController.text = value!;
                                              },
                                              controller: productWholesalePriceController,
                                              showCursor: true,
                                              cursorColor: kTitleColor,
                                              decoration: InputDecoration(
                                                labelText: lang.S.of(context).wholeSaleprice,
                                                hintText: lang.S.of(context).enterPrice,
                                              ),
                                            ),
                                          )),
                                    ]),
                                  ]),
                                )
                              ],
                            ),
                          )),
                      ResponsiveGridCol(
                          xs: 12,
                          md: screenWidth < 778 ? 12 : 4,
                          lg: screenWidth < 778 ? 12 : 4,
                          child: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                color: Colors.white,
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: Text(
                                      'Published product',
                                      style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                                    ),
                                  ),
                                  const Divider(
                                    thickness: 1.0,
                                    color: kNeutral300,
                                  ),
                                  ResponsiveGridRow(children: [
                                    ResponsiveGridCol(
                                      xs: 12,
                                      md: 6,
                                      lg: 6,
                                      child: Padding(
                                        padding: const EdgeInsets.all(10.0),
                                        child: ElevatedButton(
                                          style: ElevatedButton.styleFrom(
                                            backgroundColor: kWhite,
                                            shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.circular(4.0),
                                            ),
                                            side: const BorderSide(
                                              color: Colors.red,
                                              width: 1.0,
                                            ),
                                          ),
                                          onPressed: () {
                                            GoRouter.of(context).pop();
                                          },
                                          child: Text(
                                            lang.S.of(context).cancel,
                                            style: TextStyle(
                                              color: Colors.red,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    ResponsiveGridCol(
                                        xs: 12,
                                        md: 6,
                                        lg: 6,
                                        child: Padding(
                                          padding: const EdgeInsets.all(10.0),
                                          child: ElevatedButton(
                                            style: ElevatedButton.styleFrom(
                                              backgroundColor: kMainColor,
                                              shape: RoundedRectangleBorder(
                                                borderRadius: BorderRadius.circular(4.0),
                                              ),
                                              side: const BorderSide(
                                                color: kMainColor,
                                                width: 1.0,
                                              ),
                                            ),
                                            onPressed: () async {
                                              if (finalUserRoleModel.productUpdate == false) {
                                                EasyLoading.showError(userPermissionErrorText);
                                                return;
                                              }
                                              if (!isDemo) {
                                                if (categoryValidateAndSave()) {
                                                  try {
                                                    EasyLoading.show(status: 'Loading...', dismissOnTap: false);
                                                    final DatabaseReference productInformationRef = FirebaseDatabase
                                                        .instance
                                                        .ref("${await getUserID()}/Products/$productKey");
                                                    productModel.productName = productNameController.text;
                                                    productModel.size = sizeController.text;
                                                    productModel.color = colorController.text;
                                                    productModel.weight = weightController.text;
                                                    productModel.type = typeController.text;
                                                    productModel.productStock = quantityController.text;
                                                    // productModel.warranty = warrantyController.text;
                                                    productModel.capacity = capacityController.text;
                                                    // Use the selected values directly, not from the controllers
                                                    productModel.productCategory =
                                                        selectedCategories ?? itemCategoryController.text;
                                                    productModel.brandName = selectedBrand ?? brandNameController.text;
                                                    productModel.productUnit = selectedUnit ?? unitNameController.text;
                                                    //_____price_____________________________________
                                                    productModel.productSalePrice = productSalePriceController.text;
                                                    productModel.productPurchasePrice =
                                                        productPurchasePriceController.text;
                                                    productModel.productDealerPrice = productDealerPriceController.text;
                                                    // productModel.warehouseName=selectedWareHouse!.warehouseName;
                                                    productModel.warehouseName = selectedWareHouse?.warehouseName ??
                                                        widget.productModel.warehouseName;
                                                    productModel.productWholeSalePrice =
                                                        productWholesalePriceController.text;
                                                    productModel.productManufacturer =
                                                        productManufacturerController.text;
                                                    productModel.warranty = warrantyController.text == ''
                                                        ? ''
                                                        : '${warrantyController.text} $selectedTime';
                                                    productModel.productPicture = productPicture;
                                                    productModel.manufacturingDate = manufactureDate;
                                                    productModel.expiringDate = expireDate;
                                                    productModel.lowerStockAlert = lowerStockAlert;
                                                    productModel.taxType = selectedTaxType;
                                                    // productModel.margin = num.tryParse(marginController.text) ?? 0;
                                                    productModel.margin =
                                                        num.tryParse(marginController.text.replaceAll(',', '')) ?? 0;
                                                    productModel.excTax = num.tryParse(excTaxController.text) ?? 0;
                                                    productModel.incTax = num.tryParse(incTaxController.text) ?? 0;
                                                    productModel.groupTaxName =
                                                        selectedGroupTaxModel?.name.toString() ?? '';
                                                    productModel.groupTaxRate = selectedGroupTaxModel?.taxRate ?? 0;
                                                    productModel.subTaxes = selectedGroupTaxModel?.subTaxes ?? [];
                                                    await productInformationRef.set(productModel.toJson());
                                                    EasyLoading.showSuccess('Added Successfully',
                                                        duration: const Duration(milliseconds: 500));
                                                    ref.refresh(productProvider);
                                                    Future.delayed(const Duration(milliseconds: 100), () {
                                                      // const Product().launch(context, isNewTask: true);
                                                      context.pushReplacement('/product');
                                                    });
                                                  } catch (e) {
                                                    EasyLoading.dismiss();
                                                    ScaffoldMessenger.of(context)
                                                        .showSnackBar(SnackBar(content: Text(e.toString())));
                                                  }
                                                }
                                              } else {
                                                EasyLoading.showInfo(demoText);
                                              }
                                            },
                                            child: Text(lang.S.of(context).save),
                                          ),
                                        ))
                                  ]),

                                  ///____Image__________________
                                  Container(
                                    padding: const EdgeInsets.all(20.0),
                                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.0), color: kWhite),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        const SizedBox(height: 10.0),
                                        CustomDottedBorder(
                                          color: kLitGreyColor,
                                          child: ClipRRect(
                                            borderRadius: const BorderRadius.all(Radius.circular(12)),
                                            child: image != null || productPicture.isNotEmpty
                                                ? Stack(
                                                    children: [
                                                      // Show uploaded image if available
                                                      if (image != null)
                                                        Image.memory(
                                                          fit: BoxFit.cover,
                                                          image!,
                                                          height: 150,
                                                          width: double.infinity,
                                                        )
                                                      // Otherwise show the product picture from database
                                                      else if (productPicture.isNotEmpty)
                                                        Image.network(
                                                          productPicture,
                                                          fit: BoxFit.cover,
                                                          height: 150,
                                                          width: double.infinity,
                                                          errorBuilder: (context, error, stackTrace) {
                                                            // If network image fails, show placeholder
                                                            return _buildUploadWidget(context);
                                                          },
                                                        ),
                                                      // Close button to remove image
                                                      if (image != null || productPicture.isNotEmpty)
                                                        Positioned(
                                                          top: 5,
                                                          right: 5,
                                                          child: GestureDetector(
                                                            onTap: () {
                                                              setState(() {
                                                                image = null;
                                                                productPicture = '';
                                                              });
                                                            },
                                                            child: const CircleAvatar(
                                                              radius: 15,
                                                              backgroundColor: Colors.white,
                                                              child: Icon(
                                                                Icons.close,
                                                                color: Colors.red,
                                                                size: 20,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                    ],
                                                  )
                                                : _buildUploadWidget(context),
                                          ),
                                        ),
                                        const SizedBox(height: 10.0),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )),
                    ]),
                  ],
                ),
                const SizedBox(height: 20.0),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildUploadWidget(BuildContext context) {
    final theme = Theme.of(context);
    return Container(
      height: 150,
      alignment: Alignment.center,
      width: context.width(),
      padding: const EdgeInsets.all(10.0),
      child: Stack(
        children: [
          DropzoneView(
            onCreated: (DropzoneViewController ctrl) => controller = ctrl,
            onDropFile: (dynamic file) async {
              Uint8List fileData = await controller.getFileData(file);
              uploadFileWithDragAndDrop(fileData);
            },
            onError: (String? error) => print("Error: $error"),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SvgPicture.asset('images/blank_image.svg').onTap(() => uploadFile()),
              const SizedBox(height: 5.0),
              RichText(
                textAlign: TextAlign.center,
                text: TextSpan(
                  text: lang.S.of(context).uploadAImage,
                  style: theme.textTheme.titleMedium?.copyWith(
                    color: kGreenTextColor,
                  ),
                  children: [
                    TextSpan(
                      text: lang.S.of(context).orDragAndDropPng,
                      style: theme.textTheme.titleMedium?.copyWith(
                        color: kGreyTextColor,
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// Close button widget
  Widget _buildCloseButton() {
    return Positioned(
      top: 5,
      right: 5,
      child: GestureDetector(
        onTap: () {
          setState(() {
            image = null;
            productPicture = '';
          });
        },
        child: const CircleAvatar(
          radius: 15,
          backgroundColor: Colors.white,
          child: Icon(
            Icons.close,
            color: Colors.red,
            size: 20,
          ),
        ),
      ),
    );
  }

  bool isSerialNumberUnique({required List<String> allList, required String newSerial}) {
    for (var element in allList) {
      if (element.toLowerCase().removeAllWhiteSpace() == newSerial.toLowerCase().removeAllWhiteSpace()) {
        return false;
      }
    }
    return true;
  }
}
