import React from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { DataTable } from "primereact/datatable";
import { useEffect } from "react";
import axios from "axios";
import { useState } from "react";
import { ColumnGroup } from "primereact/columngroup";
import { Row } from "primereact/row";
import { Dropdown } from "primereact/dropdown";
import { Dialog } from "primereact/dialog";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { classNames } from "primereact/utils";
import { useRef } from "react";
import { Calendar } from "primereact/calendar";
import { Toast } from "primereact/toast";
import { AutoComplete } from "primereact/autocomplete";

function WarehouseStore({ auth }) {
  const [warehouse, SetWarehouse] = useState([]);
  const [filterState, setFilterState] = useState({
    searchText: "",
  });
  const [totalRecords, setTotalRecords] = useState(0);
  const [lazyParams, setLazyParams] = useState({
    page: 1,
    rows: 10,
  });
  const [modelShow, setModelShow] = useState(false);
  const [warehouseList, setWarehouses] = useState([]);
  const [categoryList, SetCategoryList] = useState([]);
  const [supplierList, SetSupplierList] = useState([]);
  const [existOpening, setExistOpening] = useState(false);
  const [search, setSearch] = useState({
    product: "",
  });
  const [product, setPriceProduct] = useState([]);
  const [totalQtyAll, setTotalQtyAll] = useState(0);
  const [totalValueAll, setTotalValueAll] = useState(0);
  const [totalMrpValueAll, setTotalMrpValueAll] = useState(0);
  const [totalTpValueAll, setTotalTpValueAll] = useState(0);
  const [brandId, setBrandId] = useState(null);
  const [modelId, setModelId] = useState(null);
  const [unitId, setUnitId] = useState(null);
  const [colorId, setColorId] = useState(null);
  const [originId, setOriginId] = useState(null);
  const [productTypeId, setProductTypeId] = useState(null);
  const [sizeId, setSizeId] = useState(null);

  const [brands, setBrands] = useState([]);
  const [models, setModels] = useState([]);
  const [units, setUnits] = useState([]);
  const [colors, setColors] = useState([]);
  const [origins, setOrigins] = useState([]);
  const [productTypes, setProductTypes] = useState([]);
  const [sizes, setSizes] = useState([]);
  const [showAdvancedFilter, setShowAdvancedFilter] = useState(false);

  const scroll = useRef();
  const toast = useRef();
  const FormSubmit = useRef();

  const fetchWarehouse = () => {
    axios
      .get(route("warehouse-store.view"), {
        params: {
          page: lazyParams.page,
          perPage: lazyParams.rows,
          search: filterState.searchText || undefined,
          brand_id: brandId || undefined,
          model_id: modelId || undefined,
          unit_id: unitId || undefined,
          color_id: colorId || undefined,
          origin_id: originId || undefined,
          product_type_id: productTypeId || undefined,
          size_id: sizeId || undefined,
        },
      })
      .then((response) => {
        const data = response.data.data ?? response.data.warehouse ?? [];
        SetWarehouse(data);
        setWarehouses(response.data.warehouseList ?? []);
        SetCategoryList(response.data.categoryList ?? []);
        SetSupplierList(response.data.supplier ?? []);
        setTotalRecords(response.data.total ?? data.length);
        setTotalQtyAll(response.data.total_qty_all ?? 0);
        setTotalValueAll(response.data.total_value_all ?? 0);
        setTotalMrpValueAll(response.data.total_mrp_value_all ?? 0);
        setTotalTpValueAll(response.data.total_tp_value_all ?? 0);
        setBrands(response.data.brands ?? []);
        setModels(response.data.models ?? []);
        setUnits(response.data.units ?? []);
        setColors(response.data.colors ?? []);
        setOrigins(response.data.origins ?? []);
        setProductTypes(response.data.productTypes ?? []);
        setSizes(response.data.sizes ?? []);
      });
  };

  useEffect(() => {
    fetchWarehouse();
  }, [
    lazyParams.page,
    lazyParams.rows,
    filterState.searchText,
    brandId,
    modelId,
    unitId,
    colorId,
    originId,
    productTypeId,
    sizeId,
  ]);
  // Form Control forme React Form Hook
  const {
    control,
    register,
    formState: { errors },
    handleSubmit,
    reset,
    watch,
    setValue,
  } = useForm({
    opening_date: "",
    warehouse_id: "",
    company_id: "",
    list: [
      {
        product_name: "",
        product_id: "",
        attribute_id: "",
        quantity: "",
        unit_price: "",
        unit_price: "",
        mrp_price: "",
        tp_price: "",
        total: 0,
      },
    ],
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: "list",
  });
  //Model Hide
  const hideModel = () => {
    setModelShow(false);
    reset({
      opening_date: "",
      warehouse_id: "",
      list: [
        {
          product_id: "",
          quantity: "",
          price: "",
          unit_id: "",
          category_id: "",
          total: 0,
        },
      ],
    });
  };

  // Table Header Component
  const renderHeader = () => {
    return (
      <div className="w-100% flex justify-between items-center">
        <div className="flex items-center gap-3 w-full justify-end">
          <span className="p-input-icon-left w-full sm:w-72">
            <i className="pi pi-search" />
            <InputText
              value={filterState.searchText}
              onChange={(e) =>
                setFilterState((old) => ({
                  ...old,
                  searchText: e.target.value,
                }))
              }
              placeholder="Search by product or SKU"
              className="w-full h-10 text-sm"
            />
          </span>
        </div>
      </div>
    );
  };
  const header = renderHeader();

  const quantity = () => {
    return warehouse.reduce((old, current) => {
      const qty = Number(current.quantity) || 0;
      return old + qty;
    }, 0);
  };

  const rowMrpTotal = (row) => {
    const raw = row.mrp_price_total;
    if (raw !== null && raw !== undefined && raw !== "") {
      const n = Number(raw);
      if (Number.isFinite(n)) return n;
    }
    const qty = Number(row.quantity) || 0;
    const unit = Number(row.mrp_price) || 0;
    return qty * unit;
  };

  const rowTpTotal = (row) => {
    const raw = row.tp_price_total;
    if (raw !== null && raw !== undefined && raw !== "") {
      const n = Number(raw);
      if (Number.isFinite(n)) return n;
    }
    const qty = Number(row.quantity) || 0;
    const unit = Number(row.tp_price) || 0;
    return qty * unit;
  };

  const sumMrpPage = () =>
    warehouse.reduce((acc, row) => acc + rowMrpTotal(row), 0);

  const sumTpPage = () =>
    warehouse.reduce((acc, row) => acc + rowTpTotal(row), 0);

  const sumUnitTotalPage = () =>
    warehouse.reduce(
      (old, current) => old + (Number(current.unit_price_total) || 0),
      0
    );

  // Per-unit columns (no meaningful page sum); line-total columns in same order: Unit → TP → MRP
  // business_id != 3: Product, Category, SKU, Color, Brand, Model, Size, Qty, Unit, TP, MRP, Unit tot, TP tot, MRP tot => 14
  // business_id == 3: Product, Category, SKU, Size, Qty, Unit, TP, MRP, Unit tot, TP tot, MRP tot => 11
  const visibleColumns = window?.setting?.business_id != 3 ? 14 : 11;
  const footerNumericCols = 7; // Qty + 3 unit prices (dash) + 3 line totals

  const formatNumber = new Intl.NumberFormat("en-BD", {
    maximumFractionDigits: 2,
  });

  const formatUnitCell = (value) =>
    formatNumber.format(Number(value) || 0) + " ৳";

  let footerGroup = (
    <ColumnGroup>
      <Row>
        <Column
          footer="Totals (this page):"
          colSpan={visibleColumns - footerNumericCols}
          footerStyle={{ textAlign: "right", fontWeight: "600" }}
        />
        <Column
          className="text-center"
          footer={() => formatNumber.format(quantity())}
        />
        <Column className="text-right" footer="—" />
        <Column className="text-right" footer="—" />
        <Column className="text-right" footer="—" />
        <Column
          className="text-right"
          footer={() => formatNumber.format(sumUnitTotalPage()) + " ৳"}
        />
        <Column
          className="text-right"
          footer={() => formatNumber.format(sumTpPage()) + " ৳"}
        />
        <Column
          className="text-right"
          footer={() => formatNumber.format(sumMrpPage()) + " ৳"}
        />
      </Row>
      <Row>
        <Column
          footer={
            <span className="text-xs font-semibold">
              Full totals (all matching rows): Stock{" "}
              {formatNumber.format(totalQtyAll)} | Unit value{" "}
              {formatNumber.format(totalValueAll)} ৳ | TP{" "}
              {formatNumber.format(totalTpValueAll)} ৳ | MRP{" "}
              {formatNumber.format(totalMrpValueAll)} ৳
            </span>
          }
          colSpan={visibleColumns}
          footerStyle={{ textAlign: "right" }}
        />
      </Row>
    </ColumnGroup>
  );
  // filter category
  const categoryFilter = (options) => {
    return (
      <Dropdown
        options={categoryList}
        placeholder="Select a Category"
        className="p-column-filter w-full"
        value={options.value}
        onChange={(e) => options.filterApplyCallback(e.value)}
        showClear
      />
    );
  };

  // warehouse Filter
  const warehouseFilter = (options) => {
    const warehouse = warehouseList.map((data) => data.name);

    return (
      <Dropdown
        options={warehouse}
        placeholder="Select a Warehouse"
        className="p-column-filter w-full"
        value={options.value}
        onChange={(e) => options.filterApplyCallback(e.value)}
        showClear
      />
    );
  };

  {
    /* Model Footer Content  */
  }
  const footerContent = (
    <div className="grid  grid-cols-12 ">
      <div className="col-span-12">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={hideModel}
          className="p-button-text w-13 text-sm"
        />
        {existOpening && (
          <Button
            label="Save"
            type="submit"
            onClick={() => {
              FormSubmit.current.dispatchEvent(
                new Event("submit", { bubbles: true })
              );
            }}
            icon="pi pi-check"
            className="p-button-text w-13 text-sm"
          />
        )}
      </div>
    </div>
  );
  {
    /* Model Footer Content  */
  }

  // set Error Message Multiple field
  const getFormErrorMessageMultiple = (name, index = null) => {
    return errors["list"] &&
      errors["list"][index] &&
      errors["list"][index][name] ? (
      <small className="p-error ">
        {errors["list"][index][name]["message"]}
      </small>
    ) : (
      ""
    );
  };
  // set Error Message Multiple single Field
  const getFormErrorMessageSingle = (name) => {
    return errors[name] ? (
      <small className="p-error ">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };

  const productTemplateIOptionList = (option) => {
    return (
      <div className="country-item">
        <div>
          {option.product.name} ({option.sku})
        </div>
      </div>
    );
  };

  const filterProduct = (event) => {
    setTimeout(() => {
      axios
        .post(route("purchase.product.search"), {
          data: event.query,
          supplier_id: watch("company_id"),
        })
        .then((response) => {
          setPriceProduct(response.data.produts);
        });
    }, 250);
  };

  //Set Selected Product
  const selectedItem = (item) => {
    setSearch((old) => {
      return {
        product: "",
      };
    });
    // Assuming "inputField" is the reference to your input field
    let inputValue = "";

    if (item.product) {
      inputValue += item.product.name + " ";

      if (item.sku) inputValue += "(SKU: " + item.sku + ")";
    }

    let list = watch("list");
    let find = list && list.find((e) => e.attribute_id == item.id);

    if (find) {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Your Product is already add ",
        life: 3000,
      });
    } else {
      append({
        product_name: inputValue,
        product_id: Number(item.product.id),
        attribute_id: Number(item.id),
        quantity: "",
        unit_price: Number(item.unit_price),
        tp_price: Number(item.tp),
        mrp_price: Number(item.mrp),
        total: "",
      });
    }
  };

  let list = watch("list");
  // easiest Product Store array for check
  const ProductCheck = [];
  // Update Warehouse Data  Opening Stock
  const updateWarehouse = (data) => {
    if (data.list.length != 0) {
      axios
        .put(route("warehouse-store.update", data.warehouse_id), data)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
          reset({
            opening_date: "",
            warehouse_id: "",
            list: [],
          });
          setModelShow(false);
          SetWarehouse(response.data.warehouse);
          SetSupplierList(response.data.supplier);
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must  need a product",
        life: 3000,
      });
    }
  };

  // Opening Stock Check
  const OpeningStockCheck = (id) => {
    const exist = supplierList.some((data) => {
      return (
        data.id == id &&
        data.opening_stock_qty?.opening_stock_date != null
      );
    });

    if (false) {
      setExistOpening(false);
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "This Warehouse opening stock already set",
        life: 3000,
      });
      reset({
        opening_date: "",
        company_id: watch("company_id"),
        list: [],
      });
    } else {
      setExistOpening(true);
      reset({
        opening_date: "",
        company_id: watch("company_id"),
        list: [],
      });
    }

    setValue("company_id", id);
  };
  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium ">Warehouse</h2>{" "}
          <p className="text-skin-sub-header font-semibold text-xs">
            {" "}
            Home - Warehouse List
          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />
      {/* View Table*/}
      <div className="card">
        <div className="flex justify-end mb-2">
          <Button
            type="button"
            label={showAdvancedFilter ? "Hide Filter" : "Show Filter"}
            icon={showAdvancedFilter ? "pi pi-chevron-up" : "pi pi-filter"}
            className="p-button-text text-xs"
            onClick={() => setShowAdvancedFilter((prev) => !prev)}
          />
        </div>

        {showAdvancedFilter && (
          <div className="grid grid-cols-12 gap-4 mb-4">
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Model</label>
              <Dropdown
                value={modelId}
                options={models}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setModelId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Unit</label>
              <Dropdown
                value={unitId}
                options={units}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setUnitId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Color</label>
              <Dropdown
                value={colorId}
                options={colors}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setColorId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Brand</label>
              <Dropdown
                value={brandId}
                options={brands}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setBrandId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Origin</label>
              <Dropdown
                value={originId}
                options={origins}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setOriginId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Product Type</label>
              <Dropdown
                value={productTypeId}
                options={productTypes}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setProductTypeId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <label className="block text-xs mb-1">Size</label>
              <Dropdown
                value={sizeId}
                options={sizes}
                optionLabel="name"
                optionValue="id"
                showClear
                onChange={(e) => setSizeId(e.value ?? null)}
                placeholder="Select"
                className="w-full"
              />
            </div>
          </div>
        )}
        <DataTable
          className="defulattable"
          value={warehouse}
          paginator
          lazy
          totalRecords={totalRecords}
          first={(lazyParams.page - 1) * lazyParams.rows}
          onPage={(event) => {
            setLazyParams({
              page: event.page + 1,
              rows: event.rows,
            });
          }}
          showGridlines
          rows={lazyParams.rows}
          rowsPerPageOptions={[10, 25, 50, 100]}
          dataKey="id"
          header={header}
          footerColumnGroup={footerGroup}
          emptyMessage="No warehouse found."
        >
          {/* <Column
            header="Warehouse"
            body={(e) => e.warehouse?.name ?? "N/A"}
            style={{ width: "10rem" }}
            className="text-left"
          /> */}
          <Column
            header="Product"
            body={(e) => e.attribute?.product?.name ?? "N/A"}
            style={{ width: "14rem" }}
          />
          <Column
            header="Category"
            body={(e) => e.attribute?.product?.category?.name ?? "N/A"}
            style={{ width: "10rem" }}
          />
          <Column
            header="SKU"
            body={(e) => e.attribute?.sku ?? "N/A"}
            style={{ width: "8rem" }}
          />
          {window?.setting?.business_id != 3 && (
            <Column
              header="Color"
              body={(e) => e.attribute?.color?.name ?? "N/A"}
              style={{ width: "8rem" }}
            />
          )}
          {window?.setting?.business_id != 3 && (
            <Column
              header="Brand"
              body={(e) => e.attribute?.brand?.name ?? "N/A"}
              style={{ width: "8rem" }}
            />
          )}
          {window?.setting?.business_id != 3 && (
            <Column
              header="Model"
              body={(e) => e.attribute?.model?.name ?? "N/A"}
              style={{ width: "8rem" }}
            />
          )}
          <Column
            header="Size"
            body={(e) => e.attribute?.size?.name ?? "N/A"}
            style={{ width: "8rem" }}
          />
          <Column
            header="Qty"
            body={(e) =>
              `${e.quantity ?? 0} ${e.attribute?.unit?.name ?? ""}`.trim()
            }
            className="text-center w-[6rem]"
          />
          <Column
            header="Unit price"
            body={(e) => formatUnitCell(e.unit_price)}
            className="text-right w-[7rem]"
          />
          <Column
            header="TP price"
            body={(e) => formatUnitCell(e.tp_price)}
            className="text-right w-[7rem]"
          />
          <Column
            header="MRP price"
            body={(e) => formatUnitCell(e.mrp_price)}
            className="text-right w-[7rem]"
          />
          <Column
            header="Unit total"
            body={(e) => formatUnitCell(e.unit_price_total)}
            className="text-right w-[8rem]"
          />
          <Column
            header="TP total"
            body={(e) => formatNumber.format(rowTpTotal(e)) + " ৳"}
            className="text-right w-[8rem]"
          />
          <Column
            header="MRP total"
            body={(e) => formatNumber.format(rowMrpTotal(e)) + " ৳"}
            className="text-right w-[8rem]"
          />
        </DataTable>
      </div>
      {/* View Table End*/}

      {/* Create Model*/}
      <Dialog
        header="Opening Stock "
        visible={modelShow}
        style={{ width: "80vw" }}
        footer={footerContent}
        onHide={hideModel}
      >
        <form
          onSubmit={handleSubmit(updateWarehouse)}
          className="p-fluid"
          method="POST"
          ref={FormSubmit}
        ></form>
        <div className="grid grid-cols-12 gap-5 mt-5">
          <div className="col-span-4">
            <span className="p-float-label">
              <Controller
                name="opening_date"
                control={control}
                rules={{ required: "Date is required." }}
                render={({ field, fieldState }) => (
                  <Calendar
                    {...field}
                    className="w-full h-11"
                  />
                )}
              />
              <label htmlFor="name">Opening Stock Date</label>
            </span>
            {getFormErrorMessageSingle("opening_date")}
          </div>
          <div className="col-span-4">
            <span className="p-float-label">
              <Controller
                name="company_id"
                control={control}
                rules={{
                  required: "Company Field is required",
                }}
                render={({ field, fieldState }) => (
                  <span className="p-float-label">
                    <Dropdown
                      options={supplierList}
                      id={field.name}
                      value={field.value}
                      onChange={(e) => {
                        OpeningStockCheck(e.value);
                        field.onChange(e.value);
                      }}
                      optionLabel="name"
                      optionValue="id"
                      className={
                        classNames({
                          "p-invalid":
                            fieldState.invalid,
                        }) +
                        "multiselect-custom  w-full h-11"
                      }
                    />
                    <label htmlFor={field.name}>
                      Select Company
                    </label>
                  </span>
                )}
              />
            </span>
            {getFormErrorMessageSingle("company_id")}
          </div>

          {existOpening && (
            <>
              <div className="col-span-4">
                <span className="p-float-label">
                  <Controller
                    name="warehouse_id"
                    control={control}
                    rules={{
                      required:
                        "Warehouse Field is required",
                    }}
                    render={({ field, fieldState }) => (
                      <span className="p-float-label">
                        <Dropdown
                          options={warehouseList}
                          id={field.name}
                          value={field.value}
                          onChange={(e) => {
                            field.onChange(e.value);
                          }}
                          optionLabel="name"
                          optionValue="id"
                          className={
                            classNames({
                              "p-invalid":
                                fieldState.invalid,
                            }) +
                            "multiselect-custom  w-full h-11"
                          }
                        />
                        <label htmlFor={field.name}>
                          Select Warehouse
                        </label>
                      </span>
                    )}
                  />
                </span>
                {getFormErrorMessageSingle("warehouse_id")}
              </div>
              <div className="field col-span-12 md:col-span-12 mx-[25%] mt-5">
                <Controller
                  name="product_id"
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <AutoComplete
                        value={search.product}
                        suggestions={product}
                        completeMethod={filterProduct}
                        aria-label="Product"
                        dropdown
                        itemTemplate={
                          productTemplateIOptionList
                        }
                        placeholder="Search a Product"
                        onChange={(e) => {
                          setSearch((old) => {
                            return {
                              product: e.value
                                .product
                                ? e.value
                                  .product
                                  .name +
                                " (" +
                                e.value.sku +
                                ")"
                                : e.value,
                            };
                          });
                          if (e.value.product) {
                            selectedItem(e.value);
                          }
                        }}
                        dropdownAriaLabel="Select Customer"
                        className="w-full h-11"
                      />

                      <label htmlFor={field.name}>
                        Search
                      </label>
                    </span>
                  )}
                />
              </div>
            </>
          )}
        </div>
        <div className="grid grid-cols-12 gap-6 mt-8" ref={scroll}>
          {existOpening &&
            fields.map((item, index) => {
              {
                ProductCheck.push(
                  watch(`list.${index}.product_id`)
                );
              }
              return (
                <>
                  <div className="field col-span-12 md:col-span-4">
                    <Controller
                      name={`list.${index}.product_name`}
                      control={control}
                      rules={{
                        required:
                          "Product field is required",
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <InputText
                            readOnly
                            value={field.value}
                            {...field}
                            className="h-11 w-full"
                          />
                          <label
                            htmlFor={field.value}
                          >
                            Item{"  "}
                            <b>
                              {" "}
                              {watch(
                                `list.${index}.product_label`
                              )}
                            </b>
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageMultiple(
                      `product_id`,
                      index
                    )}
                  </div>
                  <div className="field col-span-12 md:col-span-2">
                    <Controller
                      name={`list.${index}.quantity`}
                      rules={{
                        required: "Required",
                        min: {
                          value: 0,
                          message: "not Valid",
                        },
                      }}
                      control={control}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <InputText
                            type="number"
                            id={field.name}
                            value={field.value}
                            onChange={(e) => {
                              let current =
                                e.target.value
                                  .length != 0
                                  ? e.target
                                    .value
                                  : 0;
                              setValue(
                                `list.${index}.quantity`,
                                e.target.value
                              );
                              let price = watch(
                                `list.${index}.unit_price`
                              );

                              price =
                                price !=
                                  undefined
                                  ? price
                                  : 0;

                              current =
                                price * current;
                              setValue(
                                `list.${index}.total`,
                                current
                              );
                            }}
                            className={
                              classNames({
                                "p-invalid":
                                  fieldState.invalid,
                              }) +
                              "multiselect-custom  w-full h-11"
                            }
                          />
                          <label htmlFor="calendar">
                            Qty
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageMultiple(
                      `quantity`,
                      index
                    )}
                  </div>
                  <div className="field col-span-12 md:col-span-2">
                    <Controller
                      name={`list.${index}.unit_price`}
                      control={control}
                      rules={{
                        required:
                          "unit_price Field is required",
                        min: {
                          value: 1,
                          message:
                            "negative value not allow",
                        },
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <InputText
                            readOnly
                            type="number"
                            id={field.name}
                            value={field.value}
                            onChange={(e) => {
                              let current =
                                e.target.value
                                  .length != 0
                                  ? e.target
                                    .value
                                  : 0;
                              setValue(
                                `list.${index}.unit_price`,
                                e.target.value
                              );
                              let qty = watch(
                                `list.${index}.quantity`
                              );

                              qty =
                                qty != undefined
                                  ? qty
                                  : 0;
                              current =
                                current * qty;
                              setValue(
                                `list.${index}.total`,
                                current
                              );
                            }}
                            className={
                              classNames({
                                "p-invalid":
                                  fieldState.invalid,
                              }) +
                              "multiselect-custom w-full h-11"
                            }
                          />
                          <label htmlFor="calendar">
                            Unit Price
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageMultiple(
                      `unit_price`,
                      index
                    )}
                  </div>
                  <div className="field col-span-12 md:col-span-2">
                    <Controller
                      name={`list.${index}.tp_price`}
                      control={control}
                      rules={{
                        required:
                          "tp_price Field is required",
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <InputText
                            readOnly
                            type="number"
                            id={field.name}
                            value={field.value}
                            onChange={(e) => {
                              let current =
                                e.target.value
                                  .length != 0
                                  ? e.target
                                    .value
                                  : 0;
                              setValue(
                                `list.${index}.tp_price`,
                                e.target.value
                              );
                            }}
                            className={
                              classNames({
                                "p-invalid":
                                  fieldState.invalid,
                              }) +
                              "multiselect-custom w-full h-11"
                            }
                          />
                          <label htmlFor="calendar">
                            Cor.Price
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageMultiple(
                      `tp_price`,
                      index
                    )}
                  </div>
                  <div className="field col-span-12 md:col-span-2">
                    <Controller
                      name={`list.${index}.mrp_price`}
                      control={control}
                      rules={{
                        required:
                          "mrp_price Field is required",
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <InputText
                            type="number"
                            readOnly
                            id={field.name}
                            value={field.value}
                            onChange={(e) => {
                              let current =
                                e.target.value
                                  .length != 0
                                  ? e.target
                                    .value
                                  : 0;
                              setValue(
                                `list.${index}.mrp_price`,
                                e.target.value
                              );
                            }}
                            className={
                              classNames({
                                "p-invalid":
                                  fieldState.invalid,
                              }) +
                              "multiselect-custom w-full h-11"
                            }
                          />
                          <label htmlFor="calendar">
                            MRP Price
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageMultiple(
                      `mrp_price`,
                      index
                    )}
                  </div>

                  <div className="field col-span-6 md:col-span-2">
                    <Controller
                      name={`list.${index}.total`}
                      rules={{
                        required:
                          "Total Field is required",
                      }}
                      control={control}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label  p-inputtext-sm  ">
                          <InputText
                            readOnly
                            value={field.value}
                            {...field}
                            className="h-11 w-full"
                          />
                          <label htmlFor="total">
                            Total
                          </label>
                        </span>
                      )}
                    />
                  </div>
                  <div className="field col-span-6 md:col-span-10 flex gap-2  w-5  mb-3 ">
                    <span className="p-float-label  p-inputtext-sm  ">
                      <Button
                        icon="pi pi-trash"
                        onClick={(e) => {
                          e.preventDefault();
                          remove(index);
                          let lists = watch("list");
                          reset({
                            invoice_no:
                              watch("invoice_no"),

                            unit_price_date:
                              watch(
                                "unit_price_date"
                              ),
                            supplier_id:
                              watch(
                                "supplier_id"
                              ),
                            po_ref: watch("po_ref"),
                            warehouse_id:
                              watch(
                                "warehouse_id"
                              ),
                            shop_warehouse_id:
                              watch(
                                "shop_warehouse_id"
                              ),
                            list: lists.map((e) => {
                              return {
                                product_label:
                                  e[
                                  "product_label"
                                  ],
                                product_name:
                                  e[
                                  "product_name"
                                  ],
                                product_id:
                                  e[
                                  "product_id"
                                  ],
                                attribute_id:
                                  e[
                                  "attribute_id"
                                  ],

                                quantity:
                                  e[
                                  "quantity"
                                  ],
                                unit_price:
                                  e[
                                  "unit_price"
                                  ],
                                unit_price:
                                  e[
                                  "unit_price"
                                  ],
                                total: e[
                                  "total"
                                ],
                              };
                            }),
                          });
                        }}
                        className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                      />
                    </span>
                  </div>
                </>
              );
            })}
        </div>
        <hr />
        <div className="grid grid-cols-12 ">
          <div className="col-span-6 text-right mr-3">
            {list && (
              <b>
                Total QTY:{" "}
                {list.reduce(
                  (acc, item) => acc + Number(item.quantity),
                  0
                )}
              </b>
            )}
          </div>
          <div className="col-span-4 text-right mr-3">
            {list && (
              <b>
                Total Unit Price:{" "}
                {list.reduce(
                  (acc, item) => acc + Number(item.total),
                  0
                )}
              </b>
            )}
          </div>
        </div>
      </Dialog>
      {/* Create Model End*/}
    </AuthenticatedLayout>
  );
}

export default WarehouseStore;
