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

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/cupertino.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:go_router/go_router.dart';
import 'package:hugeicons/hugeicons.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:provider/provider.dart' as pro;
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/Screen/Home/total_count_widget.dart';
import 'package:salespro_admin/Screen/Purchase%20List/show_payment_popup.dart';
import 'package:salespro_admin/Screen/Widgets/Constant%20Data/constant.dart';
import 'package:salespro_admin/commas.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;
import 'package:salespro_admin/model/product_model.dart';

import '../../Provider/customer_provider.dart';
import '../../Provider/product_provider.dart';
import '../../const.dart';
import '../../model/category_model.dart';
import '../../model/customer_model.dart';
import '../../model/personal_information_model.dart';
import '../../model/purchase_transation_model.dart';
import '../../subscription.dart';
import '../Product/WarebasedProduct.dart';
import '../WareHouse/warehouse_model.dart';
import '../currency/currency_provider.dart';

class EditPurchase extends StatefulWidget {
  final PersonalInformationModel personalInformationModel;
  final bool isPosScreen;
  final PurchaseTransactionModel purchaseTransitionModel;
  final BuildContext popupContext;

  const EditPurchase({
    Key? key,
    required this.personalInformationModel,
    required this.isPosScreen,
    required this.purchaseTransitionModel,
    required this.popupContext,
  }) : super(key: key);

  @override
  State<EditPurchase> createState() => _EditPurchaseState();
}

class _EditPurchaseState extends State<EditPurchase> {
  bool uniqueCheck(String code) {
    bool isUnique = false;
    for (var item in cartList) {
      if (item.productCode == code) {
        item.productStock = (item.productStock.toInt() + 1).toString();
        isUnique = true;
        break;
      }
    }
    return isUnique;
  }

  String getTotalAmount() {
    double total = 0.0;
    for (var item in cartList) {
      total = total + (double.parse(item.productPurchasePrice) * item.productStock.toInt());
    }
    return total.toStringAsFixed(2);
  }

  List<ProductModel> cartList = [];
  List<ProductModel> increaseStockList = [];
  bool isChecked = true;
  String isSelected = 'Categories';
  String searchProductCode = '';
  String selectedCategory = 'Categories';
  String selectedCategories = 'Purchase Price';

  CustomerModel? selectedUserName;
  String? selectedUserId;
  String? invoiceNumber;
  String previousDue = "0";

  DateTime selectedDueDate = DateTime.now();
  File? image;

  TextEditingController qtyController = TextEditingController();
  TextEditingController priceController = TextEditingController();
  TextEditingController nameCodeCategoryController = TextEditingController();
  TextEditingController discountPercentageEditingController = TextEditingController();
  TextEditingController discountAmountEditingController = TextEditingController();

  double discountAmount = 0;
  double percentage = 0;

  FocusNode nameFocus = FocusNode();
  final ScrollController mainSideScroller = ScrollController();
  final ScrollController sideScroller = ScrollController();

  WareHouseModel? selectedWareHouse;
  int i = 0;
  Map<int, bool> _tappedStates = {};

  @override
  void initState() {
    super.initState();
    // Initialize with existing purchase data
    cartList = widget.purchaseTransitionModel.productList!;
    discountAmount = widget.purchaseTransitionModel.discountAmount!;
    discountAmountEditingController.text = discountAmount.toString();
    discountPercentageEditingController.text = ((discountAmount * 100) / widget.purchaseTransitionModel.totalAmount!.toDouble()).toStringAsFixed(1);

    selectedUserName = CustomerModel(
      customerName: widget.purchaseTransitionModel.customerName,
      phoneNumber: widget.purchaseTransitionModel.customerPhone,
      type: widget.purchaseTransitionModel.customerType,
      customerAddress: widget.purchaseTransitionModel.customerAddress,
      emailAddress: '',
      profilePicture: '',
      openingBalance: 0,
      remainedBalance: 0,
      dueAmount: 0,
      gst: widget.purchaseTransitionModel.customerGst,
    );

    selectedUserId = widget.purchaseTransitionModel.customerPhone;
    previousDue = "0"; // You may need to fetch actual previous due
    checkCurrentUserAndRestartApp();
  }

  @override
  Widget build(BuildContext context) {
    final currencyProvider = pro.Provider.of<CurrencyProvider>(context);
    final globalCurrency = currencyProvider.currency ?? '\$';
    final screenWidth = MediaQuery.of(context).size.width;
    final _screenSize = MediaQuery.of(context).size;
    final theme = Theme.of(context);
    List<String> allProductsNameList = [];
    List<String> allProductsCodeList = [];
    List<String> warehouseIdList = [];
    List<WarehouseBasedProductModel> warehouseBasedProductModel = [];

    return Consumer(
      builder: (context, consumerRef, __) {
        final wareHouseList = consumerRef.watch(warehouseProvider);
        AsyncValue<List<ProductModel>> productList = consumerRef.watch(productProvider);
        final customers = consumerRef.watch(allCustomerProvider);

        return Scaffold(
          backgroundColor: kDarkWhite,
          body: SingleChildScrollView(
            physics: _screenSize.width < 1240 ? ScrollPhysics() : NeverScrollableScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ///__________Header section_______________________________________
                    ResponsiveGridRow(rowSegments: 100, children: [
                      //---------------product and calculation section--------------
                      ResponsiveGridCol(
                        lg: 48,
                        md: 100,
                        xs: 100,
                        child: IntrinsicWidth(
                          child: Container(
                            decoration: const BoxDecoration(color: kWhite),
                            child: Padding(
                              padding: const EdgeInsets.all(6.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  ResponsiveGridRow(rowSegments: 120, children: [
                                    // -------------select customer-------------------------
                                    ResponsiveGridCol(
                                      xs: 60,
                                      md: 60,
                                      lg: 60,
                                      child: customers.when(data: (allCustomers) {
                                        List<String> listOfPhoneNumber = [];
                                        List<CustomerModel> suppliersList = [];

                                        for (var value1 in allCustomers) {
                                          listOfPhoneNumber.add(value1.phoneNumber.removeAllWhiteSpace().toLowerCase());
                                          if (value1.type == 'Supplier') {
                                            suppliersList.add(value1);
                                          }
                                        }
                                        return Padding(
                                          padding: const EdgeInsets.all(6.0),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment.start,
                                                children: [
                                                  Flexible(
                                                    child: Theme(
                                                        data: ThemeData(highlightColor: dropdownItemColor, focusColor: Colors.transparent, hoverColor: dropdownItemColor),
                                                        child: DropdownButtonHideUnderline(child: _getCustomerDropdown(suppliersList, globalCurrency))),
                                                  ),
                                                  GestureDetector(
                                                    onTap: () {
                                                      context.push(
                                                        '/add-customer',
                                                        extra: {
                                                          'typeOfCustomerAdd': 'Supplier',
                                                          'listOfPhoneNumber': listOfPhoneNumber,
                                                        },
                                                      );
                                                    },
                                                    child: Container(
                                                      height: 40,
                                                      width: 40,
                                                      decoration: BoxDecoration(
                                                        border: Border(
                                                          right: BorderSide(color: kNeutral300),
                                                          top: BorderSide(color: kNeutral300),
                                                          bottom: BorderSide(color: kNeutral300),
                                                        ),
                                                        borderRadius: BorderRadius.only(topRight: Radius.circular(5), bottomRight: Radius.circular(5)),
                                                        color: kMainColor50,
                                                      ),
                                                      child: const Center(
                                                        child: Icon(
                                                          FeatherIcons.userPlus,
                                                          size: 18.0,
                                                          color: kMainColor,
                                                        ),
                                                      ),
                                                    ),
                                                  )
                                                ],
                                              ),
                                              if (selectedUserId != null)
                                                Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    SizedBox(height: 2),
                                                    Text.rich(
                                                      TextSpan(text: '${lang.S.of(context).balance}: ', style: TextStyle(color: kTitleColor), children: [
                                                        TextSpan(
                                                            text: '$globalCurrency${myFormat.format(double.tryParse(previousDue) ?? 0)}',
                                                            style: TextStyle(color: Colors.red, fontWeight: FontWeight.w500))
                                                      ]),
                                                      style: theme.textTheme.bodyMedium,
                                                    )
                                                  ],
                                                )
                                            ],
                                          ),
                                        );
                                      }, error: (e, stack) {
                                        return Center(
                                          child: Text(e.toString()),
                                        );
                                      }, loading: () {
                                        return const Center(
                                          child: CircularProgressIndicator(),
                                        );
                                      }),
                                    ),
                                    //---------warehouse section-----------------------
                                    ResponsiveGridCol(
                                      xs: 60,
                                      md: 60,
                                      lg: 60,
                                      child: wareHouseList.when(
                                        data: (warehouse) {
                                          return Padding(
                                            padding: const EdgeInsets.all(6.0),
                                            child: Theme(
                                              data: ThemeData(highlightColor: dropdownItemColor, focusColor: Colors.transparent, hoverColor: dropdownItemColor),
                                              child: DropdownButtonHideUnderline(
                                                child: _getWarehouseDropdown(warehouse ?? []),
                                              ),
                                            ),
                                          );
                                        },
                                        error: (e, stack) {
                                          return Center(
                                            child: Text(
                                              e.toString(),
                                            ),
                                          );
                                        },
                                        loading: () {
                                          return const Center(
                                            child: CircularProgressIndicator(),
                                          );
                                        },
                                      ),
                                    ),
                                  ]),
                                  selectedUserId != null ? SizedBox.shrink() : SizedBox(height: 10),
                                  Scrollbar(
                                    controller: mainSideScroller,
                                    thumbVisibility: true,
                                    thickness: 6,
                                    child: SizedBox(
                                      height: _screenSize.width < 720
                                          ? 720 - 410
                                          : selectedUserId != null
                                              ? _screenSize.height - 305
                                              : _screenSize.height - 295,
                                      child: LayoutBuilder(
                                        builder: (BuildContext context, BoxConstraints constraints) {
                                          final kWidth = constraints.maxWidth;
                                          return SingleChildScrollView(
                                            controller: mainSideScroller,
                                            scrollDirection: Axis.horizontal,
                                            child: Container(
                                              constraints: BoxConstraints(
                                                minWidth: kWidth,
                                                maxHeight: 250,
                                              ),
                                              decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: kGreyTextColor.withOpacity(0.3)))),
                                              child: Theme(
                                                data: theme.copyWith(
                                                  dividerTheme: const DividerThemeData(color: Colors.transparent),
                                                ),
                                                child: SingleChildScrollView(
                                                  child: DataTable(
                                                      columnSpacing: 10,
                                                      border: const TableBorder(
                                                        horizontalInside: BorderSide(
                                                          width: 1,
                                                          color: kNeutral300,
                                                        ),
                                                      ),
                                                      dataRowColor: const WidgetStatePropertyAll(whiteColor),
                                                      headingRowColor: WidgetStateProperty.all(const Color(0xFFF8F3FF)),
                                                      showBottomBorder: false,
                                                      dividerThickness: 0.0,
                                                      headingTextStyle: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w500),
                                                      dataTextStyle: theme.textTheme.bodyLarge,
                                                      columns: [
                                                        DataColumn(label: Text(lang.S.of(context).product)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).quantity)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).purchase)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).total)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).action)),
                                                      ],
                                                      rows: List.generate(cartList.length, (index) {
                                                        TextEditingController quantityController = TextEditingController(text: cartList[index].productStock.toString());
                                                        return DataRow(cells: [
                                                          //-------------name--------------------
                                                          DataCell(Row(
                                                            crossAxisAlignment: CrossAxisAlignment.start,
                                                            children: [
                                                              Text(
                                                                cartList[index].productName,
                                                                maxLines: 1,
                                                                overflow: TextOverflow.ellipsis,
                                                              ),
                                                              SizedBox(width: 4),
                                                              Padding(
                                                                padding: const EdgeInsets.only(top: 12),
                                                                child: GestureDetector(
                                                                  onTap: () {
                                                                    _productEditPopUp(product: cartList[index], index: index);
                                                                  },
                                                                  child: HugeIcon(
                                                                    icon: HugeIcons.strokeRoundedPropertyEdit,
                                                                    color: kMainColor,
                                                                    size: 16,
                                                                  ),
                                                                ),
                                                              )
                                                            ],
                                                          )),

                                                          //-------------quantity------------------
                                                          DataCell(Center(
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.center,
                                                              children: [
                                                                GestureDetector(
                                                                  onTap: () {
                                                                    setState(() {
                                                                      int stock = int.tryParse(cartList[index].productStock) ?? 1;
                                                                      if (stock > 1) {
                                                                        stock--;
                                                                      } else {
                                                                        stock = 1;
                                                                      }
                                                                      cartList[index].productStock = stock.toString();
                                                                      toast(cartList[index].productStock = stock.toString());
                                                                    });
                                                                  },
                                                                  child: HugeIcon(
                                                                    icon: HugeIcons.strokeRoundedRemoveSquare,
                                                                    color: kNeutral400,
                                                                    size: 25,
                                                                  ),
                                                                ),
                                                                const SizedBox(width: 2),
                                                                SizedBox(
                                                                  width: 50,
                                                                  child: TextFormField(
                                                                    textAlign: TextAlign.center,
                                                                    controller: quantityController,
                                                                    onChanged: (value) {
                                                                      if (value == '' || value == '0') {
                                                                        cartList[index].productStock = '1';
                                                                      } else {
                                                                        cartList[index].productStock = value;
                                                                      }
                                                                    },
                                                                    onFieldSubmitted: (value) {
                                                                      if (value == '' || value == '0') {
                                                                        setState(() {
                                                                          cartList[index].productStock = '1';
                                                                        });
                                                                      } else {
                                                                        setState(() {
                                                                          cartList[index].productStock = value;
                                                                        });
                                                                      }
                                                                    },
                                                                    decoration: InputDecoration(
                                                                      border: InputBorder.none,
                                                                      enabledBorder: InputBorder.none,
                                                                      focusedBorder: InputBorder.none,
                                                                    ),
                                                                    inputFormatters: [
                                                                      FilteringTextInputFormatter.digitsOnly,
                                                                      LengthLimitingTextInputFormatter(6),
                                                                    ],
                                                                  ),
                                                                ),
                                                                SizedBox(width: 2),
                                                                StatefulBuilder(
                                                                  builder: (context, setStateIcon) {
                                                                    _tappedStates[index] ??= false;

                                                                    return HugeIcon(
                                                                      icon: HugeIcons.strokeRoundedPlusSignSquare,
                                                                      color: _tappedStates[index]! ? kMainColor : kNeutral400,
                                                                      size: 25,
                                                                    ).onTap(() {
                                                                      setState(() {
                                                                        int stock = int.tryParse(cartList[index].productStock) ?? 1;
                                                                        stock++;
                                                                        cartList[index].productStock = stock.toString();
                                                                        toast(stock.toString());
                                                                      });

                                                                      setStateIcon(() {
                                                                        _tappedStates[index] = true;
                                                                      });

                                                                      // Reset after delay
                                                                      Future.delayed(const Duration(milliseconds: 300), () {
                                                                        if (mounted) {
                                                                          setStateIcon(() {
                                                                            _tappedStates[index] = false;
                                                                          });
                                                                        }
                                                                      });
                                                                    });
                                                                  },
                                                                ),
                                                              ],
                                                            ),
                                                          )),
                                                          //___________Purchase____________________________________________________
                                                          DataCell(
                                                            Center(
                                                              child: Text(
                                                                '$globalCurrency${myFormat.format(double.tryParse(double.parse(cartList[index].productPurchasePrice).toStringAsFixed(2)) ?? 0)}',
                                                              ),
                                                            ),
                                                          ),
                                                          //___________Total____________________________________________________
                                                          DataCell(
                                                            Center(
                                                              child: Text(
                                                                '$globalCurrency${myFormat.format(double.tryParse((double.parse(cartList[index].productPurchasePrice) * cartList[index].productStock.toInt()).toStringAsFixed(2)) ?? 0)}',
                                                              ),
                                                            ),
                                                          ),
                                                          //_______________actions_________________________________________________
                                                          DataCell(
                                                            Center(
                                                              child: const Icon(
                                                                Icons.close_sharp,
                                                                color: redColor,
                                                                size: 20,
                                                              ).onTap(() {
                                                                setState(() {
                                                                  cartList.removeAt(index);
                                                                });
                                                              }),
                                                            ),
                                                          ),
                                                        ]);
                                                      })),
                                                ),
                                              ),
                                            ),
                                          );
                                        },
                                      ),
                                    ),
                                  ),

                                  //__________Subtotal_discount_buttons____________________________________________________
                                  Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: Column(
                                      children: [
                                        ///__________subTotal_____________________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: screenWidth < 1600 ? 4 : 6,
                                            child: Padding(
                                              padding: EdgeInsets.only(bottom: screenWidth < 577 ? 12 : 0),
                                              child: Text(
                                                'Total Item: ${cartList.length}',
                                                style: theme.textTheme.titleMedium,
                                              ),
                                            ),
                                          ),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: screenWidth < 1600 ? 8 : 6,
                                              child: Row(
                                                children: [
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 1,
                                                    child: Text(
                                                      lang.S.of(context).subTotal,
                                                      style: theme.textTheme.bodyLarge,
                                                    ),
                                                  ),
                                                  const SizedBox(width: 12),
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 3,
                                                    child: Container(
                                                      height: 33,
                                                      width: screenWidth,
                                                      decoration: BoxDecoration(
                                                        color: kMainColor.withValues(alpha: 0.1),
                                                        borderRadius: BorderRadius.circular(4),
                                                      ),
                                                      child: Align(
                                                        alignment: Alignment.centerRight,
                                                        child: Padding(
                                                          padding: const EdgeInsets.symmetric(horizontal: 16),
                                                          child: Text(
                                                            "$globalCurrency ${myFormat.format(double.tryParse((getTotalAmount().toDouble() - discountAmount).toStringAsFixed(2)) ?? 0)}",
                                                            style: theme.textTheme.titleMedium?.copyWith(color: kMainColor),
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              )),
                                        ]),
                                        const SizedBox(height: 12),

                                        ///________discount_________________________________________________
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: screenWidth < 1600 ? 4 : 6,
                                            child: const SizedBox.shrink(),
                                          ),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: screenWidth < 1600 ? 8 : 6,
                                              child: Row(
                                                children: [
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 1,
                                                    child: Text(
                                                      lang.S.of(context).discount,
                                                      style: theme.textTheme.bodyLarge,
                                                    ),
                                                  ),
                                                  const SizedBox(width: 10),
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 3,
                                                    child: Row(
                                                      children: [
                                                        Flexible(
                                                          child: SizedBox(
                                                            height: 33.0,
                                                            child: Center(
                                                              child: AppTextField(
                                                                controller: discountPercentageEditingController,
                                                                onChanged: (value) {
                                                                  if (value == '') {
                                                                    setState(() {
                                                                      percentage = 0.0;
                                                                      discountAmountEditingController.text = 0.toString();
                                                                    });
                                                                  } else {
                                                                    if (value.toInt() <= 100) {
                                                                      setState(() {
                                                                        discountAmount = double.parse(((value.toDouble() / 100) * getTotalAmount().toDouble()).toStringAsFixed(1));
                                                                        discountAmountEditingController.text = discountAmount.toString();
                                                                      });
                                                                    } else {
                                                                      setState(() {
                                                                        discountAmount = 0;
                                                                        discountAmountEditingController.clear();
                                                                        discountPercentageEditingController.clear();
                                                                      });
                                                                      EasyLoading.showError('Enter a valid Discount');
                                                                    }
                                                                  }
                                                                },
                                                                textAlign: TextAlign.right,
                                                                decoration: InputDecoration(
                                                                  contentPadding: const EdgeInsets.only(right: 6.0),
                                                                  hintText: '0',
                                                                  border: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  enabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  disabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  focusedBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  prefixIconConstraints: const BoxConstraints(maxWidth: 30.0, minWidth: 30.0),
                                                                  prefixIcon: Container(
                                                                    alignment: Alignment.center,
                                                                    height: 33,
                                                                    decoration: const BoxDecoration(
                                                                        color: Color(0xFFff5f00),
                                                                        borderRadius: BorderRadius.only(topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0))),
                                                                    child: const Text(
                                                                      '%',
                                                                      style: TextStyle(fontSize: 20.0, color: Colors.white),
                                                                    ),
                                                                  ),
                                                                ),
                                                                textFieldType: TextFieldType.PHONE,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                        const SizedBox(width: 4.0),
                                                        Flexible(
                                                          child: SizedBox(
                                                            height: 33.0,
                                                            child: Center(
                                                              child: AppTextField(
                                                                controller: discountAmountEditingController,
                                                                onChanged: (value) {
                                                                  if (value == '') {
                                                                    setState(() {
                                                                      discountAmount = 0;
                                                                      discountPercentageEditingController.text = 0.toString();
                                                                    });
                                                                  } else {
                                                                    if (value.toInt() <= getTotalAmount().toDouble()) {
                                                                      setState(() {
                                                                        discountAmount = double.parse(value);
                                                                        discountPercentageEditingController.text =
                                                                            ((discountAmount * 100) / getTotalAmount().toDouble()).toStringAsFixed(1);
                                                                      });
                                                                    } else {
                                                                      setState(() {
                                                                        discountAmount = 0;
                                                                        discountPercentageEditingController.clear();
                                                                        discountAmountEditingController.clear();
                                                                      });
                                                                      EasyLoading.showError('Enter a valid Discount');
                                                                    }
                                                                  }
                                                                },
                                                                textAlign: TextAlign.right,
                                                                decoration: InputDecoration(
                                                                  contentPadding: const EdgeInsets.only(right: 6.0),
                                                                  hintText: '0',
                                                                  border: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                                  enabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                                  disabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                                  focusedBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                                  prefixIconConstraints: const BoxConstraints(maxWidth: 30.0, minWidth: 30.0),
                                                                  prefixIcon: Container(
                                                                    alignment: Alignment.center,
                                                                    height: 33,
                                                                    decoration: const BoxDecoration(
                                                                        color: kMainColor,
                                                                        borderRadius: BorderRadius.only(topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0))),
                                                                    child: const Text(
                                                                      '\$',
                                                                      style: TextStyle(fontSize: 20.0, color: Colors.white),
                                                                    ),
                                                                  ),
                                                                ),
                                                                textFieldType: TextFieldType.PHONE,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              )),
                                        ]),

                                        ///______________buttons__________________________________________________________
                                        const SizedBox(height: 10),
                                        ResponsiveGridRow(crossAxisAlignment: CrossAxisAlignment.center, children: [
                                          ResponsiveGridCol(
                                            lg: 6,
                                            md: 6,
                                            xs: 12,
                                            child: Padding(
                                              padding: EdgeInsets.only(right: 12, bottom: screenWidth < 577 ? 12 : 0),
                                              child: OutlinedButton(
                                                style: ElevatedButton.styleFrom(padding: EdgeInsets.zero, minimumSize: Size.fromHeight(36), side: BorderSide(color: Colors.red)),
                                                onPressed: () {
                                                  Navigator.pop(widget.popupContext);
                                                },
                                                child: Text(
                                                  lang.S.of(context).cancel,
                                                ),
                                              ),
                                            ),
                                          ),
                                          ResponsiveGridCol(
                                              lg: 6,
                                              md: 6,
                                              xs: 12,
                                              child: Padding(
                                                padding: EdgeInsets.only(right: screenWidth < 577 ? 0 : 12, bottom: screenWidth < 577 ? 12 : 0),
                                                child: ElevatedButton(
                                                  style: ElevatedButton.styleFrom(
                                                    padding: EdgeInsets.zero,
                                                    minimumSize: Size.fromHeight(36),
                                                    backgroundColor: kMainColor,
                                                  ),
                                                  onPressed: () async {
                                                    if (await checkUserRolePermission(type: "purchase-update")) {
                                                      if (await Subscription.subscriptionChecker(item: 'Purchase')) {
                                                        if (cartList.isEmpty) {
                                                          EasyLoading.showError(lang.S.of(context).pleaseAddSomeProductFirst);
                                                        } else {
                                                          PurchaseTransactionModel purchaseTransitionModel = PurchaseTransactionModel(
                                                            customerName: widget.purchaseTransitionModel.customerName,
                                                            customerAddress: widget.purchaseTransitionModel.customerAddress,
                                                            customerType: widget.purchaseTransitionModel.customerType,
                                                            customerPhone: widget.purchaseTransitionModel.customerPhone,
                                                            invoiceNumber: widget.purchaseTransitionModel.invoiceNumber,
                                                            customerGst: widget.purchaseTransitionModel.customerGst,
                                                            discountAmount: discountAmount,
                                                            isPaid: true,
                                                            paymentType: 'cash',
                                                            returnAmount: 0,
                                                            dueAmount: widget.purchaseTransitionModel.dueAmount,
                                                            purchaseDate: widget.purchaseTransitionModel.purchaseDate,
                                                            totalAmount: getTotalAmount().toDouble() - discountAmount,
                                                            productList: cartList,
                                                          );
                                                          ShowEditPurchasePaymentPopUp(
                                                            purchaseTransitionModel: purchaseTransitionModel,
                                                            increaseStockList: increaseStockList,
                                                            saleListPopUpContext: widget.popupContext,
                                                            previousPaid: widget.purchaseTransitionModel.totalAmount! - widget.purchaseTransitionModel.dueAmount!.toDouble(),
                                                          ).launch(context);
                                                        }
                                                      } else {
                                                        EasyLoading.showError('Update your plan first\nPurchase Limit is over.');
                                                      }
                                                    }
                                                  },
                                                  child: Text(
                                                    lang.S.of(context).update,
                                                  ),
                                                ),
                                              )),
                                        ]),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                      //---------------product category section-----------------
                      ResponsiveGridCol(
                        lg: 12,
                        md: 100,
                        xs: 100,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: screenWidth < 1240 ? 0 : 8, vertical: screenWidth > 1240 ? 0 : 8),
                          child: Consumer(
                            builder: (_, ref, watch) {
                              AsyncValue<List<CategoryModel>> categoryList = ref.watch(categoryProvider);
                              return categoryList.when(data: (category) {
                                return Container(
                                  height: _screenSize.width < 1240
                                      ? 110
                                      : _screenSize.width < 720
                                          ? 720 - 142
                                          : _screenSize.height - 78,
                                  padding: const EdgeInsets.all(8.0),
                                  decoration: BoxDecoration(
                                    color: kWhite,
                                  ),
                                  child: SingleChildScrollView(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text('Categories', style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w500)),
                                        const SizedBox(height: 12.61),
                                        if (_screenSize.width > 1240) _buildCategoryItem('All Category', 'Categories'),
                                        SizedBox(
                                          height: screenWidth < 1240 ? 50 : null,
                                          child: ListView.builder(
                                            scrollDirection: screenWidth < 1240 ? Axis.horizontal : Axis.vertical,
                                            itemCount: category.length,
                                            shrinkWrap: true,
                                            itemBuilder: (_, i) => Wrap(
                                              direction: Axis.horizontal,
                                              children: [
                                                if (_screenSize.width < 1240 && i == 0) ...[
                                                  _buildCategoryItem('All Category', 'Categories'),
                                                  const SizedBox(width: 5),
                                                ],
                                                _buildCategoryItem(category[i].categoryName, category[i].categoryName),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              });
                            },
                          ),
                        ),
                      ),
                      //------------product list-------------------------
                      ResponsiveGridCol(
                        lg: 40,
                        md: 100,
                        xs: 100,
                        child: Padding(
                          padding: EdgeInsetsDirectional.only(start: screenWidth < 1240 ? 8 : 0, end: 8, top: 8, bottom: 8),
                          child: Column(
                            children: [
                              productList.when(data: (product) {
                                for (var element in product) {
                                  allProductsNameList.add(element.productName.removeAllWhiteSpace().toLowerCase());
                                  allProductsCodeList.add(element.productCode.removeAllWhiteSpace().toLowerCase());
                                  warehouseIdList.add(element.warehouseId.removeAllWhiteSpace().toLowerCase());
                                  warehouseBasedProductModel.add(WarehouseBasedProductModel(element.productName, element.warehouseId));
                                }
                                return SizedBox(
                                  height: 40.0,
                                  child: AppTextField(
                                    controller: nameCodeCategoryController,
                                    showCursor: true,
                                    focus: nameFocus,
                                    autoFocus: true,
                                    cursorColor: kTitleColor,
                                    onChanged: (value) {
                                      setState(() {
                                        searchProductCode = value.toLowerCase();
                                        selectedCategory = 'Categories';
                                        isSelected = "Categories";
                                      });
                                    },
                                    onFieldSubmitted: (value) {
                                      if (value != '') {
                                        if (product.isEmpty) {
                                          EasyLoading.showError('No Product Found');
                                        }
                                        for (int i = 0; i < product.length; i++) {
                                          if (product[i].productCode == value) {
                                            ProductModel cartProduct = product[i];
                                            cartProduct.serialNumber = [];
                                            cartProduct.productStock = '1';
                                            setState(() {
                                              if (!uniqueCheck(product[i].productCode)) {
                                                cartList.add(cartProduct);
                                                nameCodeCategoryController.clear();
                                                nameFocus.requestFocus();
                                                searchProductCode = '';
                                              } else {
                                                nameCodeCategoryController.clear();
                                                nameFocus.requestFocus();
                                                searchProductCode = '';
                                              }
                                            });
                                            break;
                                          }
                                          if (i + 1 == product.length) {
                                            nameCodeCategoryController.clear();
                                            nameFocus.requestFocus();
                                            EasyLoading.showError('Not found');
                                            setState(() {
                                              searchProductCode = '';
                                            });
                                          }
                                        }
                                      }
                                    },
                                    textFieldType: TextFieldType.NAME,
                                    decoration: InputDecoration(
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: kNeutral300),
                                      ),
                                      prefixIconConstraints: BoxConstraints(
                                        minHeight: 15,
                                        minWidth: 15,
                                      ),
                                      prefixIcon: Padding(
                                        padding: const EdgeInsetsDirectional.only(start: 10),
                                        child: Icon(MdiIcons.barcode, color: kTitleColor, size: 20.0),
                                      ),
                                      hintText: lang.S.of(context).nameCodeOrCateogry,
                                      hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                      border: InputBorder.none,
                                    ),
                                  ),
                                );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              }),
                              SizedBox(height: 8),
                              productList.when(data: (products) {
                                List<ProductModel> showProductVsCategory = [];
                                if (selectedCategory == 'Categories') {
                                  for (var element in products) {
                                    if ((element.productCode.toLowerCase().contains(searchProductCode) ||
                                            element.productCategory.toLowerCase().contains(searchProductCode) ||
                                            element.productName.toLowerCase().contains(searchProductCode)) &&
                                        (selectedWareHouse?.id == element.warehouseId)) {
                                      showProductVsCategory.add(element);
                                    }
                                  }
                                } else {
                                  for (var element in products) {
                                    if ((element.productCategory == selectedCategory) && (selectedWareHouse?.id == element.warehouseId)) {
                                      showProductVsCategory.add(element);
                                    }
                                  }
                                }
                                final filteredProducts = showProductVsCategory.where((product) => product.productStock != '0').toList();
                                return filteredProducts.isNotEmpty
                                    ? Container(
                                        height: context.height() - 135,
                                        decoration: const BoxDecoration(
                                          color: kDarkWhite,
                                        ),
                                        child: GridView.builder(
                                          gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                                            maxCrossAxisExtent: 137,
                                            mainAxisExtent: 170,
                                            mainAxisSpacing: 10,
                                            crossAxisSpacing: 10,
                                          ),
                                          itemCount: showProductVsCategory.length,
                                          itemBuilder: (_, i) {
                                            return Container(
                                              width: 130.0,
                                              height: 175.0,
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.circular(4.0),
                                                color: kWhite,
                                              ),
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  ///_______image_and_stock_____________________________________
                                                  Container(
                                                    height: 110,
                                                    width: MediaQuery.of(context).size.width,
                                                    alignment: Alignment.center,
                                                    decoration: const BoxDecoration(
                                                      borderRadius: BorderRadius.only(
                                                        topLeft: Radius.circular(10.0),
                                                        topRight: Radius.circular(10.0),
                                                      ),
                                                      color: Colors.white,
                                                    ),
                                                    clipBehavior: Clip.antiAlias,
                                                    child: Padding(
                                                      padding: const EdgeInsets.all(8.0),
                                                      child: Image.network(
                                                        showProductVsCategory[i].productPicture,
                                                        fit: BoxFit.cover,
                                                      ),
                                                    ),
                                                  ),
                                                  Padding(
                                                    padding: const EdgeInsets.only(top: 6.0, left: 8, right: 8, bottom: 0),
                                                    child: Column(
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        ///_______________product_name______________________________________________
                                                        Text(
                                                          showProductVsCategory[i].productName,
                                                          maxLines: 1,
                                                          overflow: TextOverflow.ellipsis,
                                                          style: theme.textTheme.bodyLarge?.copyWith(
                                                            fontSize: 15,
                                                          ),
                                                        ),
                                                        const SizedBox(height: 4.0),

                                                        ///________Purchase_price_________________________________________________
                                                        Text(
                                                          '$globalCurrency${formatValue(showProductVsCategory[i].productPurchasePrice)}',
                                                          style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w500),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ).onTap(() {
                                              setState(() {
                                                ProductModel product = ProductModel(
                                                  showProductVsCategory[i].productName,
                                                  showProductVsCategory[i].productCategory,
                                                  showProductVsCategory[i].size,
                                                  showProductVsCategory[i].color,
                                                  showProductVsCategory[i].weight,
                                                  showProductVsCategory[i].capacity,
                                                  showProductVsCategory[i].type,
                                                  showProductVsCategory[i].warranty,
                                                  showProductVsCategory[i].brandName,
                                                  showProductVsCategory[i].productCode,
                                                  '1',
                                                  showProductVsCategory[i].productUnit,
                                                  showProductVsCategory[i].productSalePrice,
                                                  showProductVsCategory[i].productPurchasePrice,
                                                  showProductVsCategory[i].productDiscount,
                                                  showProductVsCategory[i].productWholeSalePrice,
                                                  showProductVsCategory[i].productDealerPrice,
                                                  showProductVsCategory[i].productManufacturer,
                                                  showProductVsCategory[i].warehouseName,
                                                  showProductVsCategory[i].warehouseId,
                                                  showProductVsCategory[i].productPicture,
                                                  [],
                                                  manufacturingDate: showProductVsCategory[i].manufacturingDate,
                                                  lowerStockAlert: showProductVsCategory[i].lowerStockAlert,
                                                  expiringDate: showProductVsCategory[i].expiringDate,
                                                  taxType: showProductVsCategory[i].taxType,
                                                  margin: showProductVsCategory[i].margin,
                                                  excTax: showProductVsCategory[i].excTax,
                                                  incTax: showProductVsCategory[i].incTax,
                                                  groupTaxName: showProductVsCategory[i].groupTaxName,
                                                  groupTaxRate: showProductVsCategory[i].groupTaxRate,
                                                  subTaxes: showProductVsCategory[i].subTaxes,
                                                );

                                                if (!uniqueCheck(product.productCode)) {
                                                  cartList.add(product);
                                                }
                                              });
                                            });
                                          },
                                        ),
                                      )
                                    : Container(
                                        height: context.height() - 135,
                                        width: double.infinity,
                                        color: Colors.white,
                                        child: Column(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            const SizedBox(height: 30),
                                            const Image(
                                              height: 300,
                                              width: 300,
                                              image: AssetImage('images/empty_screen.png'),
                                            ),
                                            const SizedBox(height: 10),
                                            ElevatedButton(
                                              onPressed: () {
                                                context.push(
                                                  '/product/add-product',
                                                  extra: {
                                                    'allProductsCodeList': allProductsCodeList,
                                                    'warehouseBasedProductModel': [],
                                                  },
                                                );
                                              },
                                              child: Text(
                                                lang.S.of(context).addProduct,
                                                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18.0),
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              })
                            ],
                          ),
                        ),
                      )
                    ]),
                  ],
                ),
                const SizedBox(height: 20.0),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildCategoryItem(String title, String selectionValue) {
    final screenWidth = MediaQuery.of(context).size.width;
    final theme = Theme.of(context);
    return GestureDetector(
      onTap: () => setState(() {
        selectedCategory = selectionValue;
        isSelected = selectionValue;
      }),
      child: Padding(
        padding: EdgeInsets.only(
          top: 5,
          bottom: 4,
          right: screenWidth < 1240 ? 10 : 0,
        ),
        child: Container(
          width: screenWidth > 1240 ? double.infinity : null,
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4.0),
            border: isSelected == selectionValue ? Border(left: BorderSide(color: kMainColor, width: 2)) : Border.all(color: kNeutral100),
            color: isSelected == selectionValue
                ? screenWidth < 1240
                    ? Colors.transparent
                    : kMainColor100
                : Colors.transparent,
          ),
          child: Text(
            title,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: theme.textTheme.titleSmall?.copyWith(
              color: isSelected == selectionValue ? kMainColor : kDarkGreyColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  DropdownButton2<String> _getCustomerDropdown(List<CustomerModel> model, String currency) {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (var des in model) {
      var item = DropdownMenuItem(
        value: des.phoneNumber,
        child: FittedBox(
          fit: BoxFit.scaleDown,
          child: Text.rich(
            TextSpan(text: '${des.customerName} ${des.phoneNumber} ', children: [
              TextSpan(
                text: '$currency${myFormat.format(des.dueAmount)}',
                style: TextStyle(color: Colors.red),
              )
            ]),
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  color: kNeutral600,
                ),
          ),
        ),
      );
      dropDownItems.add(item);
    }
    return DropdownButton2<String>(
      iconStyleData: IconStyleData(
        icon: Icon(
          Icons.keyboard_arrow_down,
          color: kNeutral600,
        ),
      ),
      hint: const Text('Select a supplier'),
      dropdownStyleData: DropdownStyleData(
        maxHeight: 400,
        width: MediaQuery.of(context).size.width > 1600 ? 500 : 600,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
        ),
        offset: const Offset(0, -5),
        scrollbarTheme: ScrollbarThemeData(
          radius: const Radius.circular(40),
          thickness: WidgetStateProperty.all(6),
          thumbVisibility: WidgetStateProperty.all(true),
        ),
      ),
      buttonStyleData: ButtonStyleData(
        height: 40,
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5),
            bottomLeft: Radius.circular(5),
          ),
          border: Border(
            left: BorderSide(color: kNeutral300),
            bottom: BorderSide(color: kNeutral300),
            top: BorderSide(color: kNeutral300),
          ),
        ),
      ),
      menuItemStyleData: const MenuItemStyleData(
        height: 40,
        overlayColor: WidgetStatePropertyAll(kMainColor100),
        padding: EdgeInsets.symmetric(horizontal: 16),
      ),
      items: dropDownItems,
      isExpanded: true,
      selectedItemBuilder: (BuildContext context) {
        return model.map((item) {
          return Align(
            alignment: Alignment.centerLeft,
            child: Text(
              item.customerName,
              style: Theme.of(context).textTheme.titleMedium,
              textAlign: TextAlign.center,
            ),
          );
        }).toList();
      },
      value: selectedUserId,
      onChanged: dropDownItems.isEmpty
          ? null
          : (String? value) {
              if (value == null) return;

              setState(() {
                selectedUserId = value;
                for (var element in model) {
                  if (element.phoneNumber == selectedUserId) {
                    selectedUserName = element;
                    previousDue = element.dueAmount.toString();
                  }
                }
                invoiceNumber = '';
              });
            },
    );
  }

  DropdownButton2<WareHouseModel> _getWarehouseDropdown(List<WareHouseModel> list) {
    List<DropdownMenuItem<WareHouseModel>> dropDownItems = [];

    for (var element in list) {
      dropDownItems.add(DropdownMenuItem(
        value: element,
        child: Text(
          element.warehouseName,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(color: kNeutral600),
          overflow: TextOverflow.ellipsis,
        ),
      ));
      if (i == 0) {
        selectedWareHouse = element;
      }
      i++;
    }

    return DropdownButton2<WareHouseModel>(
      items: dropDownItems,
      hint: Text('Select warehouse'),
      iconStyleData: IconStyleData(
        icon: Icon(
          Icons.keyboard_arrow_down,
          color: kNeutral600,
        ),
      ),
      dropdownStyleData: DropdownStyleData(
        maxHeight: 400,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
        ),
        offset: const Offset(0, -5),
        scrollbarTheme: ScrollbarThemeData(
          radius: const Radius.circular(40),
          thickness: WidgetStateProperty.all(6),
          thumbVisibility: WidgetStateProperty.all(true),
        ),
      ),
      buttonStyleData: ButtonStyleData(
        height: 40,
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          border: Border.all(color: kNeutral300),
        ),
      ),
      menuItemStyleData: const MenuItemStyleData(
        overlayColor: WidgetStatePropertyAll(kMainColor100),
        height: 40,
        padding: EdgeInsets.symmetric(horizontal: 16),
      ),
      isExpanded: true,
      value: selectedWareHouse,
      onChanged: (WareHouseModel? value) {
        setState(() {
          selectedWareHouse = value;
        });
      },
    );
  }

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

    bool isWantToAddSerial = serialNumberList.isNotEmpty ? true : false;
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState1) {
            return Dialog(
              surfaceTintColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: SizedBox(
                width: 500,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(
                                "${product.productName} (${product.productStock})",
                                style: kTextStyle.copyWith(color: kTitleColor, fontWeight: FontWeight.bold, fontSize: 20.0),
                              ),
                              const Spacer(),
                              const Icon(FeatherIcons.x, color: kTitleColor, size: 25.0).onTap(() => {finish(context)})
                            ],
                          ),
                        ),
                        const Divider(thickness: 1.0, color: kLitGreyColor),
                        const SizedBox(height: 10.0),
                        Form(
                          key: priceKey,
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        if (value.isEmptyOrNull) {
                                          return 'Please enter Purchase Price';
                                        } else if (double.tryParse(value!) == null && !value.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      initialValue: product.productPurchasePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editedPurchasePrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).purchasePrice,
                                        hintText: lang.S.of(context).enterPurchasePrice,
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        if (value.isEmptyOrNull) {
                                          return 'Please enter Sale Price';
                                        } else if (double.tryParse(value!) == null && !value.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      initialValue: product.productSalePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editedSalePrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).salePrices,
                                        hintText: lang.S.of(context).enterSalePrice,
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 20),
                              Row(
                                children: [
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        return null;
                                      },
                                      initialValue: product.productDealerPrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editDealerPrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).dealerPrice,
                                        hintText: lang.S.of(context).enterDealePrice,
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: TextFormField(
                                      validator: (value) {
                                        return null;
                                      },
                                      initialValue: product.productWholeSalePrice,
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      onSaved: (value) {
                                        editWholesalerPrice = value!;
                                      },
                                      decoration: kInputDecoration.copyWith(
                                        border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                                        labelText: lang.S.of(context).wholeSaleprice,
                                        hintText: lang.S.of(context).enterPrice,
                                        hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                        labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 20),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Row(
                            children: [
                              Text(lang.S.of(context).addingSerialNumber),
                              const SizedBox(width: 10),
                              CupertinoSwitch(
                                  value: isWantToAddSerial,
                                  onChanged: (value) {
                                    setState1(() {
                                      isWantToAddSerial = value;
                                    });
                                  })
                            ],
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              AppTextField(
                                controller: serialController,
                                focus: serialFocus,
                                autoFocus: true,
                                showCursor: true,
                                cursorColor: kTitleColor,
                                onFieldSubmitted: (value) {
                                  if (!serialNumberList.contains(value)) {
                                    setState1(() {
                                      serialNumberList.add(value);
                                      serialController.text = '';
                                      serialFocus.requestFocus();
                                    });
                                  } else {
                                    EasyLoading.showError('Already Added');
                                    serialFocus.requestFocus();
                                  }
                                },
                                textFieldType: TextFieldType.NAME,
                                decoration: kInputDecoration.copyWith(
                                  border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                                  labelText: lang.S.of(context).serialNumber,
                                  hintText: lang.S.of(context).enterSerialNumber,
                                  hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                                  labelStyle: kTextStyle.copyWith(color: kTitleColor),
                                ),
                              ),
                              const SizedBox(height: 20.0),
                              Text(lang.S.of(context).selectSerialNumber),
                              const SizedBox(height: 10.0),
                              Container(
                                width: 500,
                                height: 100,
                                decoration: BoxDecoration(border: Border.all(width: 1, color: Colors.grey), borderRadius: const BorderRadius.all(Radius.circular(10))),
                                child: GridView.builder(
                                    shrinkWrap: true,
                                    itemCount: serialNumberList.length,
                                    itemBuilder: (BuildContext context, int index) {
                                      if (serialNumberList.isNotEmpty) {
                                        return Padding(
                                          padding: const EdgeInsets.all(10.0),
                                          child: Row(
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                '${serialNumberList[index]},',
                                              ),
                                              const SizedBox(width: 3),
                                              GestureDetector(
                                                  onTap: () {
                                                    setState1(() {
                                                      serialNumberList.removeAt(index);
                                                    });
                                                  },
                                                  child: const Icon(
                                                    Icons.close,
                                                    color: Colors.red,
                                                    size: 15,
                                                  )),
                                            ],
                                          ),
                                        );
                                      } else {
                                        return Text(lang.S.of(context).noSerialNumberFound);
                                      }
                                    },
                                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 3,
                                      childAspectRatio: 4,
                                      crossAxisSpacing: 1,
                                      mainAxisSpacing: 1,
                                    )),
                              ),
                            ],
                          ),
                        ).visible(isWantToAddSerial),
                        const SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                                padding: const EdgeInsets.only(left: 30.0, right: 30.0, top: 10.0, bottom: 10.0),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5.0),
                                  color: kRedTextColor,
                                ),
                                child: Text(
                                  lang.S.of(context).cancel,
                                  style: kTextStyle.copyWith(color: kWhite),
                                )).onTap(() {
                              GoRouter.of(context).pop();
                            }),
                            const SizedBox(width: 10.0),
                            GestureDetector(
                              onTap: () {
                                if (validateAndSave()) {
                                  cartList[index].serialNumber = serialNumberList;
                                  cartList[index].productPurchasePrice = double.parse(editedPurchasePrice).toStringAsFixed(2);
                                  cartList[index].productSalePrice = double.parse(editedSalePrice).toStringAsFixed(2);
                                  cartList[index].productDealerPrice = double.parse(editDealerPrice).toStringAsFixed(2);
                                  cartList[index].productWholeSalePrice = double.parse(editWholesalerPrice).toStringAsFixed(2);

                                  setState(() {});

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