import React from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { classNames } from "primereact/utils";
import { useState } from "react";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { Calendar } from "primereact/calendar";
import { useEffect } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useRef } from "react";
import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";
import { AutoComplete } from "primereact/autocomplete";
import { Dropdown } from "primereact/dropdown";
import SalesReturnReceiptPrint from "@/Components/SalesReturnReceiptPrint";
import { clientItemTemplate } from "@/Components/customerSearchClientTemplate";

function SalesReturn({ auth }) {
  const { permission, warehouseList } = useContext(authUser);
  const [status, setStatus] = useState("create");
  const [visible, setVisible] = useState(false);
  const scroll = useRef(null);
  const FormSubmit = useRef(null);
  const toast = useRef(null);
  const [purchase, setPurchase] = useState([]);
  const [reference_no, setReference_no] = useState();
  const [id, setId] = useState();
  const [printValue, setPrintValue] = useState([]);
  const [clients, setClients] = useState([]);
  const [invoices, setInvoices] = useState([]);
  const [salesProducts, setSalesProduct] = useState([]);
  const [salesInvoiceProducts, setSalesInvoiceProduct] = useState([]);
  const [salesReturn, setSalseReturn] = useState([]);
  const [supplier_id, setSupplier_id] = useState();
  const [warehouse, setWarehouse] = useState([]);
  const [search, setSearchValue] = useState({
    client: "",
    invoice: "",
    salesProduct: "",
  });
  const [customerFieldResetKey, setCustomerFieldResetKey] = useState(0);

  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    reset,
  } = useForm({
    reference_no: "",
    return_date: "",
    invoice_no: "",
    sales_product: "",
    costomer_id: "",

    list: [
      {
        product_label: "",
        product_name: "",
        product_id: "",
        attribute_id: "",
        sales_quantity: "",
        return_quantity: "",
        sales: "",
        return_price: "",
        total: 0,
      },
    ],
  });

  const { fields, append, prepend, remove } = useFieldArray({
    control,
    name: "list",
  });

  useEffect(() => {
    axios.get(route("sales.report.view")).then((response) => {
      setReference_no(response.data.reference);
      setSalseReturn(response.data.salesReturn);
    });

    if (!permission.includes("sales_return_super_admin_access")) {
      setValue("warehouse_id", auth.user.shop_id);
    }
  }, []);

  const TableHeader = () => {
    return (
      <div
        className={`w-100% flex ${permission.includes("sales_return")
          ? "justify-between"
          : "justify-end"
          } `}
      >
        <Button
          type="button"
          icon={<span className="pi pi-plus text-sm pr-1" />}
          label="Add"
          onClick={() => {
            setVisible(true);
            setStatus("create");
            formReset();
          }}
          className="p-button-success h-[41px]  text-[14px] "
        />
        <span className="p-input-icon-left h-10 ">
          <i className="pi pi-search" />
          <InputText className="h-[41px] w-48" placeholder="Search" />
        </span>
      </div>
    );
  };

  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>
    ) : (
      ""
    );
  };
  const getFormErrorMessageSingel = (name) => {
    return errors[name] ? (
      <small className="p-error ">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };
  // form Reset
  const formReset = () => {
    setSearchValue({
      client: "",
      invoice: "",
      salesProduct: "",
    });
    reset({
      reference_no: reference_no,
      warehouse_id: watch("warehouse_id"),
      return_date: new Date(),
      invoice_no: "",
      sales_product: "",
      costomer_id: "",
      list: [],
    });
    setCustomerFieldResetKey((k) => k + 1);
  };

  {
    /*Dilog Model Footer*/
  }
  const footerContent = (
    <div className="grid  grid-cols-12 ">
      <div className="col-span-7 flex justify-end"></div>
      <div className="col-span-5">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={() => {
            setVisible(false);
            formReset();
          }}
          className="p-button-text w-13 text-sm"
        />
        <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>
  );

  // Data Store
  const DataStore = (data) => {
    if (data.list.length != 0) {
      axios.post(route("sales.return.store", data)).then((response) => {
        setReference_no(response.data.reference);
        setSalseReturn(response.data.salesReturn);
        reset({
          reference_no: response.data.reference_no,
          reference_no: "",
          return_date: "",
          warehouse_id: watch("warehouse_id"),

          sales_product: "",
          costomer_id: "",
          list: [],
        });
        setVisible(false);

        toast.current.show({
          severity: "success",
          summary: response.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
      });
    } else {
      toast.current.show({
        severity: "error",
        summary: "Select any item",
        detail: "Proccess faield ",
        life: 3000,
        className: "custom-toast-class",
      });
    }
  };

  // Prodcut Edit
  const handelEdit = async (data) => {

    setVisible(true);
    setStatus("update");
    const c = data.client;
    const clientDisplay = c
      ? `${c.name || c.number || ""}${
          c.number && c.name ? ` (${c.number})` : ""
        }${c.user_type ? ` (${c.user_type})` : ""}`
      : "";
    setSearchValue({
      client: clientDisplay,
      invoice: data.invoice.invoice_no,
    });
    setCustomerFieldResetKey((k) => k + 1);

    setId(data.id);

    reset({
      reference_no: data.reference_no,
      return_date: new Date(data.return_date),
      costomer_id: data.customer_id,
      invoice_no: data.sales_invoice_no,
      warehouse_id: data.location_id,
      list: data.details.map((e, key) => {
        // Assuming "inputField" is the reference to your input field
        let inputValue = "";
        let inputlabel = "";

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

          if (e?.attribute?.sku)
            inputValue += "(SKU: " + e?.attribute?.sku + ")";
        }
        return {
          product_label: inputlabel,
          product_name: inputValue,
          product_id: Number(e.product_id),
          attribute_id: Number(e.attribute_id),
          sales_quantity: e.sales_quantity,
          return_quantity: e.return_qty,
          sales: e.sales_price,
          return_price: e.return_price,
          return_prv: data?.details_total[key]?.total ?? 0,
          total: e.total,
        };
      }),
    });
  };
  //  Product Update
  const DataUpdate = (data) => {
    axios.put(route("sales.return.update", id), data).then((response) => {
      setPurchase(response.data.purchases);
      setReference_no(response.data.reference_no);
      setSalseReturn(response.data.salesReturn);
      toast.current.show({
        severity: "success",
        summary: response.data.success,
        detail: "Data Insterted ",
        life: 3000,
        className: "custom-toast-class",
      });
      setVisible(false);
      reset({
        reference_no: response.data.reference_no,
        return_date: "",
        supplier_id: "",
        warehouse_id: watch("warehouse_id"),
        po_ref: "",
        warehouse_id: "",
        shop_warehouse_id: "",
        list: [],
      });
    });
  };

  const filterClient = (event) => {
    const query = event.query || "";
    setTimeout(() => {
      axios
        .post(route("customer-search"), { data: query })
        .then((response) => {
          setClients(response.data?.customer || []);
        })
        .catch(() => setClients([]));
    }, 250);
  };
  const filterInvoice = (event) => {
    const customerId = watch("costomer_id");

    // Must choose customer first; only then we fetch invoices customer-wise
    if (!customerId) {
      setInvoices([]);
      return;
    }

    setTimeout(() => {
      axios
        .post(route("invoice.search"), {
          data: event.query ? event.query : search.invoice,
          customer_id: customerId,
        })
        .then((response) => {
          setInvoices(response.data);
        });
    }, 250);
  };
  const filterSales = (event) => {
    const query = event.query.toLowerCase().trim();

    const _filteredSales = query.length
      ? salesInvoiceProducts.filter((item) => {
        const name = item.product?.name?.toLowerCase() || "";
        const sku = item?.arribute?.sku?.toLowerCase() || "";

        return name.includes(query) || sku.includes(query);
      })
      : [...salesInvoiceProducts];

    setSalesProduct(_filteredSales);
  };

  const handelDelete = (id) => {
    let con = confirm("Are you sure to remove");

    if (con) {
      axios
        .post(route("sales.return.delete", [id, 1]))
        .then((response) => {
          setReference_no(response.data.reference);
          setSalseReturn(response.data.salesReturn);

          toast.current.show({
            severity: "success",
            summary: response.data.success,
            detail: "Data Deleted ",
            life: 3000,
            className: "custom-toast-class",
          });
        });
    }
  };

  const productTempelateIOptionList = (option) => {
    return (
      <div>
        <div>
          {(option.product?.name ||
            option.product_name ||
            option.name ||
            "")}{" "}
          {option?.arribute?.sku && `(${option.arribute.sku})`}
        </div>
      </div>
    );
  };

  const selectedItem = (item) => {
    let inputValue = "";
    let inputlabel = "";

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

      if (item?.arribute?.sku)
        inputValue += "(" + item?.arribute?.sku + ")";
    }

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

    setValue("supplier_id", supplier_id);
    if (find) {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Your Product is already add ",
        life: 3000,
      });
    } else {
      append({
        product_label: inputlabel,
        product_name: inputValue,
        product_id: Number(item.product.id),
        attribute_id: Number(item.attribute_id),
        sales_quantity: item.qty,
        sales: Number(item.price ?? 0) - Number(item.after_discount ?? 0),
        return_price: Number(item.price ?? 0) - Number(item.after_discount ?? 0),
        return_prv: item?.salesReturn?.total_qty ?? 0,
        total: "",
      });
    }
  };

  // check Selected Value
  var ProductCheck = [];
  return (
    <>
      {printValue && <SalesReturnReceiptPrint salesReturn={printValue} />}
      <AuthenticatedLayout
        user={auth.user}
        header={
          <>
            <h2 className="text-skin-header font-medium ">
              Sales Return
            </h2>{" "}
            <p className="text-skin-sub-header font-semibold text-xs">
              {" "}
              Home - SalesReturn{" "}
            </p>
          </>
        }
        headerButton={<></>}
      >
        <Toast ref={toast} />
        {/* View Table*/}
        <div className="card">
          <DataTable
            className="defulattable"
            value={salesReturn}
            paginator
            showGridlines
            rows={10}
            dataKey="id"
            header={TableHeader}
            emptyMessage="No Purchase found."
          >
            <Column
              field="reference_no"
              body={(data) => {
                return <b>{data.reference_no} </b>;
              }}
              header="Reference No"
            />
            <Column
              field="return_date"
              body={(date) => {
                return new Date(
                  date.return_date
                ).toLocaleDateString("en-US");
              }}
              header="Return Date"
            />

            <Column
              field="coustomer"
              filterField="client.name"
              body={(data) => {
                return data.client
                  ? data.client.name +
                  " (" +
                  data.client.code +
                  ")"
                  : "N/A";
              }}
              header="Coustomer"
            />
            <Column
              field="purchase_received_date"
              body={(date) => {
                return date.invoice.invoice_no;
              }}
              header="Invoice No"
            />

            <Column field="location.name" header="Warehouse/Shop" />
            <Column field="total" header="Total" />
            <Column
              header="Action"
              body={(rowData) => (
                <>
                  {" "}
                  <ConfirmPopup />{" "}
                  {permission.includes("sales_return") &&
                    true && (
                      <Button
                        icon="pi pi-pencil"
                        className="p-button-rounded p-button-success  px-3 py-2  w-10 h-10 font-medium"
                        onClick={() => {
                          handelEdit(rowData);
                        }}
                      />
                    )}
                  {permission.includes("sales_return") && (
                    <Button
                      icon="pi pi-print"
                      className="p-button-rounded p-button-info px-3 py-2   w-10 h-10  font-medium"
                      onClick={() => {
                        setPrintValue(rowData);
                        setTimeout(() => {
                          window.print();
                        }, 100);
                      }}
                    />
                  )}
                  <Button
                    icon="pi pi-trash"
                    data-id={rowData.id}
                    onClick={() => {
                      handelDelete(rowData.id);
                    }}
                    className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                  />
                </>
              )}
              dataType="boolean"
              bodyClassName="text-center"
              style={{ minWidth: "8rem" }}
              className="space-x-1"
            />
          </DataTable>
        </div>
        {/* View Table End*/}

        <Dialog
          header={() => (status == "create" ? "Create" : "Update")}
          visible={visible}
          style={{ width: "85vw", height: "100vh" }}
          onHide={() => {
            setVisible(false);
            formReset();
          }}
          footer={footerContent}
        >
          <form
            onSubmit={
              status == "create"
                ? handleSubmit(DataStore)
                : handleSubmit(DataUpdate)
            }
            ref={FormSubmit}
            onKeyPress={(event) => {
              if (event.key === "Enter") {
                event.preventDefault();
              }
            }}
          >
            <div className=" grid grid-cols-12 gap-6 mt-6  ">
              <div className="field col-span-12 md:col-span-4">
                <Controller
                  name="reference_no"
                  control={control}
                  rules={{
                    required: "Invoice field is required",
                  }}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <InputText
                        id={field.name}
                        readOnly
                        value={
                          status == "create"
                            ? reference_no
                            : field.value
                        }
                        className={
                          classNames({
                            "p-invalid":
                              fieldState.invalid,
                          }) + "w-full h-11"
                        }
                      />
                      <label htmlFor="calendar">
                        Reference No
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("reference_no")}
              </div>
              <div className="field col-span-12 md:col-span-4">
                <Controller
                  name="return_date"
                  control={control}
                  rules={{
                    required: "Date field is required",
                  }}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <Calendar
                        className="w-full h-11"
                        id="calendar"
                        inputId={field.name}
                        value={field.value}
                        onChange={(e) => {
                          // Convert to UTC date at midnight to prevent timezone shift
                          const utcDate = new Date(
                            Date.UTC(
                              e.value.getFullYear(),
                              e.value.getMonth(),
                              e.value.getDate(),
                              0,
                              0,
                              0
                            )
                          );

                          field.onChange(utcDate);
                        }}
                      />
                      <label htmlFor="calendar">
                        Return Date
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("return_date")}
              </div>
              {permission.includes(
                "sales_return_super_admin_access"
              ) && (
                  <div className="field col-span-12 md:col-span-4">
                    <Controller
                      name="warehouse_id"
                      control={control}
                      rules={{
                        required: "Date field is required",
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <Dropdown
                            optionLabel="name"
                            optionValue="id"
                            options={warehouseList}
                            value={field.value}
                            onChange={(e) => {
                              field.onChange(e.value);
                              reset({
                                reference_no:
                                  watch(
                                    "reference_no"
                                  ),
                                return_date:
                                  watch(
                                    "return_date"
                                  ),
                                warehouse_id:
                                  e.value,
                                costomer_id: "",
                                invoice_no: "",
                                sales_product: "",
                                list: [],
                              });
                              setSearchValue({
                                client: "",
                                invoice: "",
                                salesProduct: "",
                              });
                              setInvoices([]);
                              setSalesInvoiceProduct([]);
                              setCustomerFieldResetKey((k) => k + 1);
                            }}
                            disabled={
                              !permission.includes(
                                "sales_return_super_admin_access"
                              )
                            }
                            showClear
                            placeholder="Select a Warehouse"
                            className="w-full"
                          />
                          <label>
                            Select Warehouse/Shop
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageSingel("warehouse_id")}
                  </div>
                )}

              <div className="field col-span-12 md:col-span-4">
                <Controller
                  name="costomer_id"
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <AutoComplete
                        key={customerFieldResetKey}
                        value={search.client}
                        suggestions={clients}
                        completeMethod={filterClient}
                        aria-label="Coustomer"
                        dropdown
                        itemTemplate={clientItemTemplate}
                        onChange={(e) => {
                          const val = e.value;
                          if (val && typeof val === "object" && val.id) {
                            reset({
                              return_date: watch("return_date"),
                              warehouse_id: watch("warehouse_id"),
                              reference_no: watch("reference_no"),
                              invoice_no: "",
                              sales_product: "",
                              costomer_id: val.id,
                              list: [],
                            });
                            setSalesInvoiceProduct([]);
                            const displayName = val.name || val.number || "";
                            const numberPart =
                              val.number && val.name ? ` (${val.number})` : "";
                            const userTypePart = val.user_type
                              ? ` (${val.user_type})`
                              : "";
                            setSearchValue((old) => ({
                              ...old,
                              client: displayName + numberPart + userTypePart,
                              invoice: "",
                              salesProduct: "",
                            }));
                            setInvoices([]);
                          } else if (typeof val === "string") {
                            setSearchValue((old) => ({ ...old, client: val }));
                          } else if (val == null) {
                            field.onChange(null);
                            reset({
                              return_date: watch("return_date"),
                              warehouse_id: watch("warehouse_id"),
                              reference_no: watch("reference_no"),
                              invoice_no: "",
                              sales_product: "",
                              costomer_id: "",
                              list: [],
                            });
                            setSearchValue((old) => ({
                              ...old,
                              client: "",
                              invoice: "",
                              salesProduct: "",
                            }));
                            setInvoices([]);
                            setSalesInvoiceProduct([]);
                          }
                        }}
                        dropdownAriaLabel="Select Coustomer"
                        className={
                          classNames({
                            "p-invalid": fieldState.invalid,
                          }) + " w-full h-11"
                        }
                      />
                      <label htmlFor={field.name}>Customer</label>
                    </span>
                  )}
                />
              </div>
              <div className="field col-span-12 md:col-span-4">
                <Controller
                  name="invoice_no"
                  control={control}
                  rules={{
                    required: "Invoice number is required",
                  }}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <AutoComplete
                        name="invoice_no"
                        value={search.invoice}
                        suggestions={invoices}
                        completeMethod={filterInvoice}
                        disabled={!watch("costomer_id")}
                        aria-label="invoice_no"
                        dropdown
                        field="invoice_no"
                        onChange={(e) => {
                          // Typing: keep the text in the input, defer heavy resets until an item is selected
                          if (typeof e.value === "string") {
                            setSearchValue((old) => ({
                              ...old,
                              invoice: e.value,
                            }));
                            return;
                          }

                          // Selecting an invoice object
                          reset({
                            costomer_id: watch("costomer_id"),
                            return_date: watch("return_date"),
                            warehouse_id: watch("warehouse_id"),
                            reference_no: watch("reference_no"),
                            list: [],
                          });

                          setValue(
                            "invoice_no",
                            e.value?.id ? e.value.id : null
                          );
                          setSupplier_id(e.value?.supplier_id);

                          if (e.value == "") {
                            setInvoices([]);
                          }

                          if (e.value?.details) {
                            setSalesInvoiceProduct(
                              e.value.details.map((item) => {
                                const matchingReturn =
                                  (e.value.sales_return || []).find(
                                    (list) =>
                                      list.product_id === item.product_id &&
                                      list.attribute_id === item.attribute_id
                                  );

                                return {
                                  ...item,
                                  salesReturn:
                                    matchingReturn || null, // Include matching sales return or null if not found
                                };
                              })
                            );
                          }

                          setSearchValue((old) => ({
                            ...old,
                            invoice: e.value?.invoice_no ?? "",
                            salesProduct: "",
                          }));
                        }}
                        dropdownAriaLabel="Select invoice"
                        className="w-full h-11"
                      />

                      <label htmlFor={field.name}>
                        Sales Invoice No
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("invoice_no")}
              </div>

              <div className="field col-span-12 md:col-span-4">
                <Controller
                  name="sales_product"
                  control={control}
                  // rules={{ required: "Product  is required" }}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <AutoComplete
                        value={search.salesProduct}
                        suggestions={salesProducts}
                        completeMethod={filterSales}
                        aria-label="sales_product"
                        dropdown
                        itemTemplate={
                          productTempelateIOptionList
                        }
                        onChange={(e) => {
                          setValue(
                            "sales_product",
                            e.value.product_id
                              ? e.value.product_id
                              : null
                          );

                          setSearchValue((old) => ({
                            ...old,
                            salesProduct:
                              e.value.product?.name ||
                              e.value.product_name ||
                              e.value.name ||
                              e.value,
                          }));

                          if (e.value.product) {
                            selectedItem(e.value);
                          }
                        }}
                        dropdownAriaLabel="Select invoice"
                        className="w-full h-11"
                      />

                      <label htmlFor={field.name}>
                        Sales Product
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("sales_product")}
              </div>
            </div>
            <div
              className=" grid grid-cols-12 gap-6 mt-10 "
              ref={scroll}
            >
              {fields.map((item, index) => {
                {
                  ProductCheck.push(
                    watch(`list.${index}.product_id`)
                  );
                }
                return (
                  <>
                    <div className="field col-span-12 md:col-span-2">
                      <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
                              className="mb-5"
                              htmlFor={
                                field.value
                              }
                            >
                              Item{"  "}
                            </label>
                          </span>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `product_id`,
                        index
                      )}
                    </div>
                    <div className="field col-span-12 md:col-span-2">
                      <Controller
                        name={`list.${index}.sales_quantity`}
                        rules={{
                          required: "Required",
                          min: {
                            value: 0,
                            message: "not Valid",
                          },
                        }}
                        control={control}
                        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}.sales_quantity`,
                                  e.target
                                    .value
                                );
                                let price =
                                  watch(
                                    `list.${index}.sales`
                                  );

                                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">
                              Sale Qty{" "}
                              <b className="text-[8px] text-red-600">
                                Prv Return Qty :{" "}
                                {watch(
                                  `list.${index}.return_prv`
                                )}
                              </b>
                            </label>
                          </span>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `sales_quantity`,
                        index
                      )}
                    </div>
                    <div className="field col-span-12 md:col-span-2">
                      <Controller
                        name={`list.${index}.return_quantity`}
                        rules={{
                          required: "Required",
                          min: {
                            value: 0,
                            message: "not Valid",
                          },
                          max: {
                            value:
                              status == "create"
                                ? watch(
                                  `list.${index}.sales_quantity`
                                ) -
                                watch(
                                  `list.${index}.return_prv`
                                )
                                : watch(
                                  `list.${index}.sales_quantity`
                                ),
                            message: "Over qty",
                          },
                        }}
                        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}.return_quantity`,
                                  e.target
                                    .value
                                );
                                let price =
                                  watch(
                                    `list.${index}.return_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">
                              Return Qty
                            </label>
                          </span>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `return_quantity`,
                        index
                      )}
                    </div>

                    <div className="field col-span-6 md:col-span-2">
                      <Controller
                        name={`list.${index}.sales`}
                        rules={{
                          required:
                            "sales Field is required",
                          min: {
                            value: 0,
                            message:
                              "nagative value not allow",
                          },
                        }}
                        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">
                              sales Price
                            </label>
                          </span>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `sales`,
                        index
                      )}
                    </div>
                    <div className="field col-span-6 md:col-span-2">
                      <Controller
                        name={`list.${index}.return_price`}
                        rules={{
                          required:
                            "Return Field is required",
                          min: {
                            value: 0,
                            message:
                              "nagative value not allow",
                          },
                          max: {
                            value:
                              watch(
                                `list.${index}.sales`
                              ) *
                              watch(
                                `list.${index}.sales_quantity`
                              ),
                            message: "Over Return",
                          },
                        }}
                        control={control}
                        render={({
                          field,
                          fieldState,
                        }) => (
                          <span className="p-float-label  p-inputtext-sm  ">
                            <InputText
                              value={field.value}
                              {...field}
                              onChange={(e) => {
                                let current =
                                  e.target
                                    .value
                                    .length !=
                                    0
                                    ? e
                                      .target
                                      .value
                                    : 0;
                                setValue(
                                  `list.${index}.return_price`,
                                  e.target
                                    .value
                                );
                                let qty = watch(
                                  `list.${index}.return_quantity`
                                );

                                qty =
                                  qty !=
                                    undefined
                                    ? qty
                                    : 0;
                                current =
                                  current *
                                  qty;
                                setValue(
                                  `list.${index}.total`,
                                  current
                                );
                              }}
                              className="h-11 w-full"
                            />
                            <label htmlFor="total">
                              Return Price
                            </label>
                          </span>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `return_price`,
                        index
                      )}
                    </div>

                    <div className="field col-span-6 md:col-span-1">
                      <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-1 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({
                              ...watch(),
                            });
                          }}
                          className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                        />
                      </span>
                    </div>
                  </>
                );
              })}
            </div>
          </form>
        </Dialog>

        {/* Print Receipt Component */}
      </AuthenticatedLayout>
    </>
  );
}
export default SalesReturn;
