// ignore_for_file: unused_result, use_build_context_synchronously
import 'dart:io';

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/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:image_picker/image_picker.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/GlobalComponents/button_global.dart';
import 'package:mobile_pos/Provider/category,brans,units_provide.dart';
import 'package:mobile_pos/Screens/Products/brands_list.dart';
import 'package:mobile_pos/Screens/Products/category_list.dart';
import 'package:mobile_pos/Screens/Products/unit_list.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/product_model.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../GlobalComponents/Model/category_model.dart';
import '../../Provider/product_provider.dart';
import '../../Services/check user subscription limit/check_subscription_limit_for_user.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../subscription.dart';
import '../Warehouse/warehouse_model.dart';
import '../tax report/tax_model.dart';
import 'excel_upload screen.dart';

class AddProductAI extends StatefulWidget {
  const AddProductAI({
    super.key,
    required this.productNameList,
    required this.productCodeList,
    required this.warehouseBasedProductModel,
    this.product, // For update functionality
    this.isUpdate = false, // Flag to indicate update mode
  });

  final List<WarehouseBasedProductModel> warehouseBasedProductModel;
  final List<String> productNameList;
  final List<String> productCodeList;
  final ProductModel? product;
  final bool isUpdate;

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

class AddProductAIState extends State<AddProductAI> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();

  // State variables
  bool _isLoading = false;
  GetCategoryAndVariationModel _categoryData =
      GetCategoryAndVariationModel(variations: [], categoryName: '');
  String _productCategory = '';
  String _productCategoryHint = lang.S.current.selectProductCategory;
  String _brandName = '';
  String _brandNameHint = lang.S.current.selectBrand;
  String _productUnit = '';
  String _productUnitHint = lang.S.current.selectUnit;
  String _productPicture = _defaultProductImage;
  XFile? _pickedImage;
  File _imageFile = File('No File');
  String _imagePath = 'No Data';
  WareHouseModel? _selectedWareHouse;
  GroupTaxModel? _selectedGroupTaxModel;
  String _selectedTaxType = 'Inclusive';
  double _totalAmount = 0.0;
  String _excTaxAmount = '';
  String _incTaxAmount = '';

  // Product details
  int _lowerStockAlert = 5;
  String? _expireDate;
  String? _manufactureDate;

  // Price text values
  String _mrpText = '';
  String _purchaseText = '';
  String _wholesaleText = '';
  String _dealerText = '';

  // Form controllers
  final TextEditingController _productNameController = TextEditingController();
  final TextEditingController _productCodeController = TextEditingController();
  final TextEditingController _productDescriptionController = TextEditingController();
  final TextEditingController _productPurchasePriceController = TextEditingController();
  final TextEditingController _productSalePriceController = TextEditingController();
  final TextEditingController _productWholesalePriceController = TextEditingController();
  final TextEditingController _productDealerPriceController = TextEditingController();
  final TextEditingController _stockController = TextEditingController();
  final TextEditingController _totalAmountController = TextEditingController();
  final TextEditingController _incTaxController = TextEditingController();
  final TextEditingController _excTaxController = TextEditingController();
  final TextEditingController _marginController = TextEditingController();
  final TextEditingController _expireDateController = TextEditingController();
  final TextEditingController _manufactureDateController = TextEditingController();
  final TextEditingController _sizeController = TextEditingController();
  final TextEditingController _colorController = TextEditingController();
  final TextEditingController _weightController = TextEditingController();
  final TextEditingController _capacityController = TextEditingController();
  final TextEditingController _typeController = TextEditingController();
  final TextEditingController _discountController = TextEditingController();
  final TextEditingController _manufacturerController = TextEditingController();
  final TextEditingController _lowStockAlertController = TextEditingController();

  // Constants
  static const String _defaultProductImage =
      'https://firebasestorage.googleapis.com/v0/b/maanpos.appspot.com/o/Customer%20Picture%2FNo_Image_Available.jpeg?alt=media&token=3de0d45e-0e4a-4a7b-b115-9d6722d5031f';
  static const List<String> _taxStatusOptions = ['Inclusive', 'Exclusive'];

  @override
  void initState() {
    super.initState();
    _productPurchasePriceController.addListener(_calculateTotal);
    _marginController.addListener(_adjustSalesPrices);
    _initDefaultValues();

    // If in update mode, populate fields with existing product data
    if (widget.isUpdate && widget.product != null) {
      _populateProductData(widget.product!);
    }
  }

  void _initDefaultValues() {
    _marginController.text = '0';
    _lowStockAlertController.text = '5';
  }

  void _populateProductData(ProductModel product) {
    _productNameController.text = product.productName;
    _productCategory = product.productCategory;
    _productCategoryHint = product.productCategory;
    _productDescriptionController.text = product.productDescription;
    _sizeController.text = product.size;
    _colorController.text = product.color;
    _weightController.text = product.weight;
    _capacityController.text = product.capacity;
    _typeController.text = product.type;
    _brandName = product.brandName;
    _brandNameHint = product.brandName;
    _productCodeController.text = product.productCode;
    _stockController.text = product.productStock;
    _productUnit = product.productUnit;
    _productUnitHint = product.productUnit;
    _productSalePriceController.text = myFormat.format(int.parse(product.productSalePrice));
    _productPurchasePriceController.text =
        myFormat.format(int.parse(product.productPurchasePrice));
    _discountController.text = product.productDiscount;
    _productWholesalePriceController.text =
        myFormat.format(int.parse(product.productWholeSalePrice));
    _productDealerPriceController.text = myFormat.format(int.parse(product.productDealerPrice));
    _manufacturerController.text = product.productManufacturer;
    _lowStockAlertController.text = product.lowerStockAlert.toString();
    _selectedTaxType = product.taxType;
    _marginController.text = product.margin.toString();
    _productPicture = product.productPicture;

    // Set dates if available
    if (product.manufacturingDate != null) {
      _manufactureDate = product.manufacturingDate;
      _manufactureDateController.text =
          DateFormat.yMMMd().format(DateTime.parse(product.manufacturingDate!));
    }

    if (product.expiringDate != null) {
      _expireDate = product.expiringDate;
      _expireDateController.text =
          DateFormat.yMMMd().format(DateTime.parse(product.expiringDate!));
    }

    // Set initial price values
    _mrpText = product.productSalePrice;
    _purchaseText = product.productPurchasePrice;
    _wholesaleText = product.productWholeSalePrice;
    _dealerText = product.productDealerPrice;

    // Calculate tax amounts
    _incTaxAmount = product.incTax.toString();
    _excTaxAmount = product.excTax.toString();
    _incTaxController.text = myFormat.format(product.incTax.toInt());
    _excTaxController.text = myFormat.format(product.excTax.toInt());

    // Set tax selection if available
    if (product.groupTaxName.isNotEmpty) {
      // This would need to be set based on available tax data
    }
  }

  @override
  void dispose() {
    _productPurchasePriceController.removeListener(_calculateTotal);
    _marginController.removeListener(_adjustSalesPrices);

    // Dispose all controllers
    _productNameController.dispose();
    _productCodeController.dispose();
    _productDescriptionController.dispose();
    _productPurchasePriceController.dispose();
    _productSalePriceController.dispose();
    _productWholesalePriceController.dispose();
    _productDealerPriceController.dispose();
    _stockController.dispose();
    _totalAmountController.dispose();
    _incTaxController.dispose();
    _excTaxController.dispose();
    _marginController.dispose();
    _expireDateController.dispose();
    _manufactureDateController.dispose();
    _sizeController.dispose();
    _colorController.dispose();
    _weightController.dispose();
    _capacityController.dispose();
    _typeController.dispose();
    _discountController.dispose();
    _manufacturerController.dispose();
    _lowStockAlertController.dispose();

    super.dispose();
  }

  // Image handling methods
  Future<void> _showImageSourceDialog() async {
    await showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
          child: SizedBox(
            height: 200.0,
            width: MediaQuery.of(context).size.width - 80,
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _ImageSourceOption(
                    icon: Icons.photo_library_rounded,
                    label: lang.S.of(context).gallary,
                    onTap: () => _pickImage(ImageSource.gallery),
                  ),
                  const SizedBox(width: 40.0),
                  _ImageSourceOption(
                    icon: Icons.camera,
                    label: lang.S.of(context).camera,
                    onTap: () => _pickImage(ImageSource.camera),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Future<void> _pickImage(ImageSource source) async {
    final pickedImage = await _picker.pickImage(source: source);
    if (pickedImage != null) {
      setState(() {
        _pickedImage = pickedImage;
        _imageFile = File(pickedImage.path);
        _imagePath = pickedImage.path;
      });
      Navigator.pop(context);
    }
  }

  Future<void> _uploadImage() async {
    if (_imagePath == 'No Data') return;

    try {
      EasyLoading.show(
        status: '${lang.S.of(context).Uploading}... ',
        dismissOnTap: false,
      );

      final snapshot = await FirebaseStorage.instance
          .ref('Product Picture/${DateTime.now().millisecondsSinceEpoch}')
          .putFile(_imageFile);

      final url = await snapshot.ref.getDownloadURL();

      setState(() {
        _productPicture = url.toString();
      });
    } on firebase_core.FirebaseException catch (e) {
      EasyLoading.dismiss();
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.code.toString())));
    }
  }

  // Price calculation methods
  void _calculateTotal() {
    final saleAmountText = _productPurchasePriceController.text.replaceAll(',', '');
    final saleAmount = double.tryParse(saleAmountText) ?? 0.0;

    if (_selectedGroupTaxModel != null) {
      final taxRate = double.parse(_selectedGroupTaxModel!.taxRate.toString());
      final totalAmount = _calculateTotalAmount(saleAmount, taxRate);

      setState(() {
        _totalAmountController.text = totalAmount.toStringAsFixed(2);
        _totalAmount = totalAmount;
      });
    }
  }

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

  void _adjustSalesPrices() {
    final margin = double.tryParse(_marginController.text) ?? 0;
    final purchasePrice = double.tryParse(_purchaseText) ?? 0;
    double salesPrice = 0;
    double excPrice = 0;

    final taxAmount = _calculateAmountFromPercentage(
        double.tryParse(_selectedGroupTaxModel?.taxRate.toString() ?? '0') ?? 0, purchasePrice);

    if (_selectedTaxType == 'Inclusive') {
      salesPrice = purchasePrice + _calculateAmountFromPercentage(margin, purchasePrice);
      _mrpText = salesPrice.toString();
      _dealerText = salesPrice.toString();
      _wholesaleText = salesPrice.toString();
      _incTaxAmount = salesPrice.toString();
      _excTaxAmount = salesPrice.toString();
    } else {
      salesPrice =
          purchasePrice + _calculateAmountFromPercentage(margin, purchasePrice) + taxAmount;
      excPrice = purchasePrice + taxAmount;
      _mrpText = salesPrice.toString();
      _dealerText = salesPrice.toString();
      _wholesaleText = salesPrice.toString();
      _incTaxAmount = salesPrice.toString();
      _excTaxAmount = excPrice.toString();
    }

    // Update controllers with formatted values
    _updatePriceControllers(salesPrice, excPrice);
  }

  double _calculateAmountFromPercentage(double percentage, double price) {
    return price * (percentage / 100);
  }

  void _updatePriceControllers(double salesPrice, double excPrice) {
    _productSalePriceController.text = _formatNumber(salesPrice.toString());
    _productWholesalePriceController.text = _formatNumber(salesPrice.toString());
    _productDealerPriceController.text = _formatNumber(salesPrice.toString());
    _incTaxController.text = _formatNumber(salesPrice.toString());
    _excTaxController.text = _formatNumber(excPrice.toString());
  }

  String _formatNumber(String value) {
    final cleanValue = value.replaceAll(',', '');
    final doubleValue = double.tryParse(cleanValue);
    return doubleValue != null ? myFormat.format(doubleValue.toInt()) : '0';
  }

  // Validation methods
  bool _checkProductName({required String name, required String id}) {
    // For update mode, allow the same name for the same product
    if (widget.isUpdate && widget.product != null) {
      if (name.toLowerCase() == widget.product!.productName.toLowerCase() &&
          id == widget.product!.warehouseId) {
        return true;
      }
    }

    return !widget.warehouseBasedProductModel.any((element) =>
        element.productName.toLowerCase() == name.toLowerCase() && element.productID == id);
  }

  bool _checkProductCode({required String code}) {
    // For update mode, allow the same code for the same product
    if (widget.isUpdate && widget.product != null) {
      if (code.toLowerCase() == widget.product!.productCode.toLowerCase()) {
        return true;
      }
    }

    return !widget.productCodeList.contains(code.toLowerCase().removeAllWhiteSpace());
  }

  bool _validateForm() {
    final form = _formKey.currentState;
    if (form?.validate() ?? false) {
      form!.save();
      return true;
    }
    return false;
  }

  // Save product method
  Future<void> _saveProduct(WidgetRef ref) async {
    if (!_validateForm()) return;

    if (isDemo) {
      EasyLoading.showError(demoText);
      return;
    }

    // For new products, check subscription limits
    if (!widget.isUpdate) {
      final allowed = await SubscriptionService.checkLimit(
        type: SubscriptionLimitType.products,
        context: context,
      );

      if (!allowed) return;
    }

    setState(() => _isLoading = true);

    try {
      EasyLoading.show(status: '${lang.S.of(context).loading}...', dismissOnTap: false);

      final hasInternet = await InternetConnection().hasInternetAccess;
      if (hasInternet && _imagePath != 'No Data') {
        await _uploadImage();
      }

      if (widget.isUpdate && widget.product != null) {
        await _updateProductInDatabase();
      } else {
        await _createProductInDatabase();
      }

      EasyLoading.dismiss();
      _resetFormAndNavigate(ref);
    } catch (e) {
      setState(() => _isLoading = false);
      EasyLoading.dismiss();
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString())));
    }
  }

  Future<void> _createProductInDatabase() async {
    final productRef = FirebaseDatabase.instance.ref().child(constUserId).child('Products');
    productRef.keepSynced(true);

    final productModel = ProductModel(
      productName: _productNameController.text,
      productCategory: _productCategory,
      productDescription: _productDescriptionController.text,
      size: _sizeController.text,
      color: _colorController.text,
      weight: _weightController.text,
      capacity: _capacityController.text,
      type: _typeController.text,
      brandName: _brandName,
      productCode: _productCodeController.text,
      productStock: _stockController.text,
      productUnit: _productUnit,
      productSalePrice: _mrpText.replaceAll(',', ''),
      productPurchasePrice: _purchaseText.replaceAll(',', ''),
      productDiscount: _discountController.text,
      productWholeSalePrice: _wholesaleText.replaceAll(',', ''),
      productDealerPrice: _dealerText.replaceAll(',', ''),
      productManufacturer: _manufacturerController.text,
      warehouseName: _selectedWareHouse?.warehouseName ?? '',
      warehouseId: _selectedWareHouse?.id ?? '',
      productPicture: _productPicture,
      expiringDate: _expireDate,
      manufacturingDate: _manufactureDate,
      lowerStockAlert: int.parse(_lowStockAlertController.text),
      serialNumber: [],
      taxType: _selectedTaxType,
      margin: num.tryParse(_marginController.text) ?? 0,
      excTax: num.tryParse(_excTaxAmount) ?? 0,
      incTax: num.tryParse(_incTaxAmount) ?? 0,
      groupTaxName: _selectedGroupTaxModel?.name ?? '',
      groupTaxRate: _selectedGroupTaxModel?.taxRate ?? 0,
      subTaxes: _selectedGroupTaxModel?.subTaxes ?? [],
    );

    await productRef.push().set(productModel.toJson());
    Subscription.decreaseSubscriptionLimits(itemType: 'products', context: context);
  }

  Future<void> _updateProductInDatabase() async {
    if (widget.product == null) return;

    final productRef = FirebaseDatabase.instance
        .ref()
        .child(constUserId)
        .child('Products')
        .child(''); // Assuming ProductModel has a key field

    final productModel = ProductModel(
      productName: _productNameController.text,
      productCategory: _productCategory,
      productDescription: _productDescriptionController.text,
      size: _sizeController.text,
      color: _colorController.text,
      weight: _weightController.text,
      capacity: _capacityController.text,
      type: _typeController.text,
      brandName: _brandName,
      productCode: _productCodeController.text,
      productStock: _stockController.text,
      productUnit: _productUnit,
      productSalePrice: _mrpText.replaceAll(',', ''),
      productPurchasePrice: _purchaseText.replaceAll(',', ''),
      productDiscount: _discountController.text,
      productWholeSalePrice: _wholesaleText.replaceAll(',', ''),
      productDealerPrice: _dealerText.replaceAll(',', ''),
      productManufacturer: _manufacturerController.text,
      warehouseName: _selectedWareHouse!.warehouseName,
      warehouseId: _selectedWareHouse!.id,
      productPicture: _productPicture,
      expiringDate: _expireDate,
      manufacturingDate: _manufactureDate,
      lowerStockAlert: int.parse(_lowStockAlertController.text),
      serialNumber: widget.product!.serialNumber,
      // Keep existing serial numbers
      taxType: _selectedTaxType,
      margin: num.tryParse(_marginController.text) ?? 0,
      excTax: num.tryParse(_excTaxAmount) ?? 0,
      incTax: num.tryParse(_incTaxAmount) ?? 0,
      groupTaxName: _selectedGroupTaxModel?.name ?? '',
      groupTaxRate: _selectedGroupTaxModel?.taxRate ?? 0,
      subTaxes: _selectedGroupTaxModel?.subTaxes ?? [],
      // key: widget.product!.key, // Preserve the key for update
    );

    await productRef.update(productModel.toJson());
  }

  void _resetFormAndNavigate(WidgetRef ref) {
    ref.refresh(categoryProvider);
    ref.refresh(brandsProvider);
    ref.refresh(productProvider);
    Navigator.pop(context, true);
  }

  // Widget builders
  Widget _buildImagePicker() {
    return GestureDetector(
      onTap: _showImageSourceDialog,
      child: Stack(
        children: [
          Container(
            height: 120,
            width: 120,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black54, width: 1),
              borderRadius: const BorderRadius.all(Radius.circular(120)),
              image: DecorationImage(
                image: _imagePath == 'No Data'
                    ? NetworkImage(_productPicture) as ImageProvider
                    : FileImage(_imageFile),
                fit: BoxFit.cover,
              ),
            ),
          ),
          Positioned(
            bottom: 0,
            right: 0,
            child: Container(
              height: 35,
              width: 35,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.white, width: 2),
                borderRadius: const BorderRadius.all(Radius.circular(120)),
                color: kMainColor,
              ),
              child: const Icon(
                Icons.camera_alt_outlined,
                size: 20,
                color: Colors.white,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildBarcodeScannerButton() {
    return GestureDetector(
      onTap: _scanBarcode,
      child: Container(
        height: 60.0,
        width: 100.0,
        padding: const EdgeInsets.all(5.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0),
          border: Border.all(color: kGreyTextColor),
        ),
        child: const Image(image: AssetImage('images/barcode.png')),
      ),
    );
  }

  Future<void> _scanBarcode() async {
    await showDialog(
      context: context,
      useSafeArea: true,
      builder: (context) => _BarcodeScannerDialog(
        onBarcodeDetected: (barcode) {
          setState(() {
            _productCodeController.text = barcode;
          });
        },
      ),
    );
  }

  // Field builders
  Widget _buildProductNameField() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        decoration: InputDecoration(
          floatingLabelBehavior: FloatingLabelBehavior.always,
          border: const OutlineInputBorder(),
          labelText: lang.S.of(context).productName,
          hintText: lang.S.of(context).enterProductName,
        ),
        validator: (value) {
          if (value?.removeAllWhiteSpace().toLowerCase().isEmptyOrNull ?? true) {
            return '${lang.S.of(context).productNameIsRequired}.';
          } else if (!_checkProductName(
            name: value!,
            id: _selectedWareHouse?.id ?? '',
          )) {
            return '${lang.S.of(context).productNameAlreadyExistsInThisWarehouse}.';
          }
          return null;
        },
        controller: _productNameController,
      ),
    );
  }

  Widget _buildCategoryField() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        readOnly: true,
        onTap: () async {
          final data = await const CategoryList().launch(context);
          setState(() {
            _productCategory = data.categoryName;
            _productCategoryHint = data.categoryName;
            _categoryData = data;
          });
        },
        decoration: InputDecoration(
          floatingLabelBehavior: FloatingLabelBehavior.always,
          hintText: _productCategoryHint,
          labelText: lang.S.of(context).category,
          border: const OutlineInputBorder(),
          suffixIcon: const Icon(Icons.keyboard_arrow_down),
        ),
      ),
    );
  }

  Widget _buildVariationFields() {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _sizeController,
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).size,
                    hintText: lang.S.of(context).enterSize,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ).visible(_categoryData.variations.contains('Size')),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _colorController,
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).color,
                    hintText: lang.S.of(context).enterColor,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ).visible(_categoryData.variations.contains('Color')),
          ],
        ),
        Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _weightController,
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).weight,
                    hintText: lang.S.of(context).enterWeight,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ).visible(_categoryData.variations.contains('Weight')),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _capacityController,
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).capacity,
                    hintText: lang.S.of(context).enterCapacity,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ).visible(_categoryData.variations.contains('Capacity')),
          ],
        ),
        Padding(
          padding: const EdgeInsets.all(10.0),
          child: TextFormField(
            controller: _typeController,
            decoration: InputDecoration(
              floatingLabelBehavior: FloatingLabelBehavior.always,
              labelText: lang.S.of(context).type,
              hintText: lang.S.of(context).enterType,
              border: const OutlineInputBorder(),
            ),
          ),
        ).visible(_categoryData.variations.contains('Type')),
      ],
    );
  }

  Widget _buildBrandField() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        readOnly: true,
        onTap: () async {
          final data = await const BrandsList().launch(context);
          setState(() {
            _brandName = data;
            _brandNameHint = data;
          });
        },
        decoration: InputDecoration(
          floatingLabelBehavior: FloatingLabelBehavior.always,
          hintText: _brandNameHint,
          labelText: lang.S.of(context).brand,
          border: const OutlineInputBorder(),
          suffixIcon: const Icon(Icons.keyboard_arrow_down),
        ),
      ),
    );
  }

  Widget _buildProductCodeField() {
    return Row(
      children: [
        Expanded(
          flex: 3,
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              controller: _productCodeController,
              validator: (value) {
                if (value.isEmptyOrNull) {
                  return lang.S.of(context).productCodeIsRequired;
                } else if (!_checkProductCode(code: value!)) {
                  return '${lang.S.of(context).thisProductAlreadyAdded}!';
                }
                return null;
              },
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).productCode,
                hintText: lang.S.of(context).enterProductCodeOrScan,
                border: const OutlineInputBorder(),
              ),
            ),
          ),
        ),
        Expanded(
          flex: 1,
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: _buildBarcodeScannerButton(),
          ),
        ),
      ],
    );
  }

  Widget _buildStockAndUnitFields() {
    return Row(
      children: [
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*$')),
              ],
              controller: _stockController,
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value.isEmptyOrNull) {
                  return lang.S.of(context).stockIsRequired;
                }
                return null;
              },
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).stocks,
                hintText: lang.S.of(context).enterStocks,
                border: const OutlineInputBorder(),
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              readOnly: true,
              onTap: () async {
                final data = await const UnitList().launch(context);
                setState(() {
                  _productUnit = data;
                  _productUnitHint = data;
                });
              },
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                hintText: _productUnitHint,
                labelText: lang.S.of(context).units,
                border: const OutlineInputBorder(),
                suffixIcon: const Icon(Icons.keyboard_arrow_down),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAdditionalFields(AsyncValue<List<WareHouseModel>> wareHouseList) {
    return Row(
      children: [
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              controller: _manufacturerController,
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).menufeturer,
                hintText: lang.S.of(context).enterManufacturer,
                border: const OutlineInputBorder(),
              ),
            ),
          ),
        ),
        wareHouseList.when(
          data: (warehouse) {
            return Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: FormField(
                  builder: (FormFieldState<dynamic> field) {
                    return InputDecorator(
                      decoration: InputDecoration(
                        enabledBorder: const OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8.0)),
                          borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                        ),
                        contentPadding: const EdgeInsets.all(8.0),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                        labelText: lang.S.of(context).warehouse,
                      ),
                      child: DropdownButtonHideUnderline(
                        child: _buildWarehouseDropdown(warehouse),
                      ),
                    );
                  },
                ),
              ),
            );
          },
          error: (e, stack) {
            return Center(child: Text(e.toString()));
          },
          loading: () {
            return const Center(child: CircularProgressIndicator());
          },
        ),
      ],
    );
  }

  DropdownButton<WareHouseModel> _buildWarehouseDropdown(List<WareHouseModel> list) {
    final items = list.map((element) {
      return DropdownMenuItem(
        value: element,
        child: SizedBox(
          width: 110,
          child: Text(
            element.warehouseName,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      );
    }).toList();

    return DropdownButton(
      isExpanded: true,
      items: items,
      value: _selectedWareHouse ?? list.first,
      onChanged: (value) {
        setState(() {
          _selectedWareHouse = value!;
        });
      },
    );
  }

  Widget _buildTaxFields(AsyncValue<List<GroupTaxModel>> groupTax) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: Row(
        children: [
          groupTax.when(
            data: (groupTaxList) {
              return Expanded(
                child: FormField(
                  builder: (FormFieldState<dynamic> field) {
                    return InputDecorator(
                      decoration: InputDecoration(
                        enabledBorder: const OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8.0)),
                          borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                        ),
                        contentPadding: const EdgeInsets.all(8.0),
                        floatingLabelBehavior: FloatingLabelBehavior.always,
                        labelText: lang.S.of(context).applicableTax,
                      ),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<GroupTaxModel>(
                          hint: Text(lang.S.of(context).selectTax),
                          items: groupTaxList.map((e) {
                            return DropdownMenuItem<GroupTaxModel>(
                              value: e,
                              child: Text(e.name),
                            );
                          }).toList(),
                          value: _selectedGroupTaxModel,
                          onChanged: (value) {
                            setState(() {
                              _selectedGroupTaxModel = value;
                              _calculateTotal();
                              _adjustSalesPrices();
                            });
                          },
                        ),
                      ),
                    );
                  },
                ),
              );
            },
            error: (e, stack) {
              return Center(child: Text(e.toString()));
            },
            loading: () {
              return const Center(child: CircularProgressIndicator());
            },
          ),
          const SizedBox(width: 20.0),
          Expanded(
            child: FormField(
              builder: (FormFieldState<dynamic> field) {
                return InputDecorator(
                  decoration: InputDecoration(
                    enabledBorder: const OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(8.0)),
                      borderSide: BorderSide(color: kBorderColorTextField, width: 2),
                    ),
                    contentPadding: const EdgeInsets.all(8.0),
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).taxType,
                  ),
                  child: DropdownButtonHideUnderline(
                    child: _buildTaxTypeDropdown(),
                  ),
                );
              },
            ),
          )
        ],
      ),
    );
  }

  DropdownButton<String> _buildTaxTypeDropdown() {
    final items = _taxStatusOptions.map((des) {
      return DropdownMenuItem(
        value: des,
        child: Text(des),
      );
    }).toList();

    return DropdownButton(
      isExpanded: true,
      items: items,
      value: _selectedTaxType,
      onChanged: (value) {
        setState(() {
          _selectedTaxType = value!;
          _adjustSalesPrices();
        });
      },
    );
  }

  Widget _buildMarginAndTaxAmountFields() {
    return Row(
      children: [
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              controller: _marginController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).margin,
                hintText: '0',
                border: const OutlineInputBorder(),
              ),
            ),
          ),
        ),
        Visibility(
          visible: _selectedTaxType == 'Inclusive',
          child: Expanded(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextFormField(
                readOnly: true,
                controller: _incTaxController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  floatingLabelBehavior: FloatingLabelBehavior.always,
                  labelText: '${lang.S.of(context).incTax}:',
                  hintText: '0',
                  border: const OutlineInputBorder(),
                ),
              ),
            ),
          ),
        ),
        Visibility(
          visible: _selectedTaxType == 'Exclusive',
          child: Expanded(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextFormField(
                controller: _excTaxController,
                readOnly: true,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  floatingLabelBehavior: FloatingLabelBehavior.always,
                  labelText: " ${lang.S.of(context).excTax}:",
                  hintText: '0',
                  border: const OutlineInputBorder(),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPriceFields() {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _productPurchasePriceController,
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    _purchaseText = value.replaceAll(',', '');
                    _adjustSalesPrices();
                    final 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 lang.S.of(context).purchasePriceIsRequired;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).purchasePrice,
                    hintText: lang.S.of(context).enterPurchasePrice,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _productSalePriceController,
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    _mrpText = value.replaceAll(',', '');
                    final formattedText = myFormat.format(int.parse(_mrpText));
                    _productSalePriceController.value = _productSalePriceController.value.copyWith(
                      text: formattedText,
                      selection: TextSelection.collapsed(offset: formattedText.length),
                    );
                  },
                  validator: (value) {
                    if (value.isEmptyOrNull) {
                      return lang.S.of(context).MRPIsRequired;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).MRP,
                    hintText: lang.S.of(context).enterMrpOrRetailerPirce,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ),
          ],
        ),
        Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _productWholesalePriceController,
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    _wholesaleText = value.replaceAll(',', '');
                    final formattedText = myFormat.format(int.parse(_wholesaleText));
                    _productWholesalePriceController.value =
                        _productWholesalePriceController.value.copyWith(
                      text: formattedText,
                      selection: TextSelection.collapsed(offset: formattedText.length),
                    );
                  },
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).wholeSalePrice,
                    hintText: lang.S.of(context).enterWholeSalePrice,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: TextFormField(
                  controller: _productDealerPriceController,
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    _dealerText = value.replaceAll(',', '');
                    final formattedText = myFormat.format(int.parse(_dealerText));
                    _productDealerPriceController.value =
                        _productDealerPriceController.value.copyWith(
                      text: formattedText,
                      selection: TextSelection.collapsed(offset: formattedText.length),
                    );
                  },
                  decoration: InputDecoration(
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    labelText: lang.S.of(context).dealerPrice,
                    hintText: lang.S.of(context).enterDealerPrice,
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildDateFields() {
    return Row(
      children: [
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              readOnly: true,
              controller: _manufactureDateController,
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).manufactureDate,
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  onPressed: () async {
                    final DateTime? picked = await showDatePicker(
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2015, 8),
                      lastDate: DateTime(2101),
                      context: context,
                    );
                    setState(() {
                      if (picked != null) {
                        _manufactureDateController.text = DateFormat.yMMMd().format(picked);
                        _manufactureDate = picked.toString();
                      }
                    });
                  },
                  icon: const Icon(FeatherIcons.calendar),
                ),
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextFormField(
              readOnly: true,
              controller: _expireDateController,
              validator: (value) {
                return null;
              },
              decoration: InputDecoration(
                floatingLabelBehavior: FloatingLabelBehavior.always,
                labelText: lang.S.of(context).expireDate,
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  onPressed: () async {
                    final DateTime? picked = await showDatePicker(
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2015, 8),
                      lastDate: DateTime(2101),
                      context: context,
                    );
                    setState(() {
                      if (picked != null) {
                        _expireDateController.text = DateFormat.yMMMd().format(picked);
                        _expireDate = picked.toString();
                      }
                    });
                  },
                  icon: const Icon(FeatherIcons.calendar),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildLowStockField() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        controller: _lowStockAlertController,
        onChanged: (value) {
          _lowerStockAlert = int.tryParse(value) ?? 5;
        },
        decoration: InputDecoration(
          floatingLabelBehavior: FloatingLabelBehavior.always,
          labelText: lang.S.of(context).lowStockAlert,
          hintText: lang.S.of(context).enterLowStockAlertQuantity,
          border: const OutlineInputBorder(),
        ),
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      ),
    );
  }

  Widget _buildDescriptionField() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        maxLines: 3,
        keyboardType: TextInputType.multiline,
        controller: _productDescriptionController,
        decoration: InputDecoration(
          floatingLabelBehavior: FloatingLabelBehavior.always,
          border: const OutlineInputBorder(),
          labelText: lang.S.of(context).describtion,
          hintText: lang.S.of(context).enterDescription,
        ),
      ),
    );
  }

  Widget _buildBulkUploadButton() {
    return IconButton(
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ExcelUploader(
              previousProductCode: widget.productCodeList,
              previousProductName: widget.productNameList,
            ),
          ),
        );
      },
      style: ButtonStyle(
          backgroundColor: MaterialStatePropertyAll(kMainColor.withValues(alpha: 0.2))),
      icon: Row(
        children: [
          Text(
            lang.S.of(context).bulkUpload,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 8, color: Colors.white),
          ),
          const SizedBox(width: 3),
          const Image(height: 25, width: 25, image: AssetImage('images/excel-file.png')),
        ],
      ),
    );
  }

  Widget _buildSaveButton(WidgetRef ref) {
    return ButtonGlobal(
      iconColor: kMainColor,
      iconWidget: null,
      buttontext:
          widget.isUpdate ? lang.S.of(context).updateProduct : lang.S.of(context).saveAndPublish,
      buttonDecoration: kButtonDecoration.copyWith(
          color: kMainColor, borderRadius: const BorderRadius.all(Radius.circular(30))),
      onPressed: _isLoading ? null : () => _saveProduct(ref),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kMainColor,
      appBar: AppBar(
        backgroundColor: kMainColor,
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(
          widget.isUpdate ? lang.S.of(context).updateProduct : lang.S.of(context).addNewProduct,
          style: GoogleFonts.poppins(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [_buildBulkUploadButton()],
        centerTitle: true,
        elevation: 0,
      ),
      body: Container(
        alignment: Alignment.topCenter,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius:
              BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
        ),
        child: Consumer(
          builder: (context, ref, __) {
            final wareHouseList = ref.watch(warehouseProvider);
            final groupTax = ref.watch(groupTaxProvider);

            return SingleChildScrollView(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0, top: 10),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    _buildProductNameField(),
                    _buildCategoryField(),
                    _buildVariationFields(),
                    _buildBrandField(),
                    _buildProductCodeField(),
                    _buildStockAndUnitFields(),
                    _buildAdditionalFields(wareHouseList),
                    _buildTaxFields(groupTax),
                    _buildMarginAndTaxAmountFields(),
                    _buildPriceFields(),
                    _buildDateFields(),
                    _buildLowStockField(),
                    _buildDescriptionField(),
                    _buildImagePicker(),
                    const SizedBox(height: 20),
                    _buildSaveButton(ref),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

// Helper widgets
class _ImageSourceOption extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;

  const _ImageSourceOption({
    required this.icon,
    required this.label,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 60.0, color: kMainColor),
          Text(label, style: GoogleFonts.poppins(fontSize: 20.0, color: kMainColor)),
        ],
      ),
    );
  }
}

class _BarcodeScannerDialog extends StatefulWidget {
  final Function(String) onBarcodeDetected;

  const _BarcodeScannerDialog({required this.onBarcodeDetected});

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

class __BarcodeScannerDialogState extends State<_BarcodeScannerDialog> {
  late MobileScannerController controller;

  @override
  void initState() {
    super.initState();
    controller = MobileScannerController(torchEnabled: false, returnImage: false);
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadiusDirectional.circular(6.0)),
      child: Column(
        children: [
          AppBar(
            backgroundColor: Colors.transparent,
            iconTheme: const IconThemeData(color: Colors.white),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          Expanded(
            child: MobileScanner(
              fit: BoxFit.contain,
              controller: controller,
              onDetect: (capture) {
                final barcodes = capture.barcodes;
                if (barcodes.isNotEmpty) {
                  widget.onBarcodeDetected(barcodes.first.rawValue!);
                  Navigator.pop(context);
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}
