import { React, useState, useContext } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";
import { Dropdown } from "primereact/dropdown";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { useEffect } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useRef } from "react";
import { FilterMatchMode, FilterOperator } from "primereact/api";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import PurchaseMakerPrient from "./PurchaseMakerPrient";
import PurchaseMakerPrint2Inch from "./PurchaseMakerPrint2Inch";
import PurchaseMakerPrint3Inch from "./PurchaseMakerPrint3Inch";
import { classNames } from "primereact/utils";
import { Calendar } from "primereact/calendar";
import { authUser } from "@/Components/AuthProvider";
import { AutoComplete } from "primereact/autocomplete";
import StockProductDropdown from "@/Components/ProductDropdown";
import DynamicFieldGroup from "@/Components/DynamicFieldGroup";

function PurchaseMaker({ auth }) {
  const { permission } = useContext(authUser);
  const [modelshow, SetShowModel] = useState(false);
  const [product, SetProduct] = useState([]);
  const [supplier, SetSupplier] = useState([]);
  const toast = useRef(null);
  const [makers, setMaker] = useState([]);
  const [modelStatus, SetModelStatus] = useState("create");
  const [id, setid] = useState(null);
  const [po_no, setPoNo] = useState(null);
  const componentRef = useRef(null);
  const [printValue, setPrintValue] = useState([]);
  const [filters, setFilters] = useState({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    po_no: {
      operator: FilterOperator.AND,
      constraints: [
        { value: null, matchMode: FilterMatchMode.ENDS_WITH },
      ],
    },
    po_date: {
      operator: FilterOperator.AND,
      constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }],
    },
  });
  const [globalFilterValue, setGlobalFilterValue] = useState("");
  const [info, setInfo] = useState([]);
  const [search, setSearch] = useState({
    product: "",
  });
  const FormSubmit = useRef(null);
  const [lowStockDialogVisible, setLowStockDialogVisible] = useState(false);
  const [lowStockProducts, setLowStockProducts] = useState([]);
  const [loadingLowStock, setLoadingLowStock] = useState(false);
  const [selectedLowStockProducts, setSelectedLowStockProducts] = useState([]);
  const [outOfStockDialogVisible, setOutOfStockDialogVisible] = useState(false);
  const [outOfStockProducts, setOutOfStockProducts] = useState([]);
  const [loadingOutOfStock, setLoadingOutOfStock] = useState(false);
  const [selectedOutOfStockProducts, setSelectedOutOfStockProducts] = useState([]);

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    setError,
    formState: { errors },
    watch,
  } = useForm({
    po_no: "",
    po_date: "",
    supplier_id: "",
    list: [
      {
        product: "",
        product_id: "",
        attribute_id: "",
        stock_qty: "",
        carton_box: "",
        quantity: "",
        price: "",
        total: 0,
      },
    ],
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: "list",
  });

  // Get invoice print mode from settings (A4 / 3 inch / 2 inch)
  const getInvoicePrintMode = () => {
    if (typeof window !== "undefined" && window.setting && window.setting.invoice_print_mode) {
      return window.setting.invoice_print_mode;
    }
    return "a4"; // Default to A4
  };

  const printMode = getInvoicePrintMode();

  useEffect(() => {
    axios.get(route("purchase-makers.view")).then((response) => {
      setPoNo(response.data.po_no);
      setMaker(getMaker(response.data.maker));
      SetSupplier(response.data.supplier);
      reset({ po_no: response.data.po_no });
      setInfo(response.data.info);
    });
  }, []);

  const getMaker = (data) => {
    return [...(data || [])].map((d) => {
      d.po_date = new Date(d.po_date);
      return d;
    });
  };

  const StoreData = (data) => {
    axios
      .post(route("purchase-makers.store"), data)
      .then((respose) => {
        toast.current.show({
          severity: "success",
          summary: respose.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
        SetShowModel(false);
        setMaker(respose.data.maker);
        setPoNo(respose.data.po_no);
        resetForm();
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          setError(field, {
            type: "manual",
            message: errors[field][0],
          });
        });
        Object.keys(errors).forEach((field) => {
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail: errors[field][0],
            life: 3000,
          });
        });
      });
  };

  //Form Reset]
  const resetForm = (invoice_no = po_no) => {
    reset({
      po_no: invoice_no,
      po_date: "",
      supplier_id: "",
      list: [],
    });
  };

  //Table Data Search

  const onGlobalFilterChange = (e) => {
    const value = e.target.value;

    let _filters = { ...filters };

    _filters["global"].value = value;

    setFilters(_filters);
    setGlobalFilterValue(value);
  };

  {
    /* Table Header Component  */
  }
  const renderHeader = () => {
    return (
      <div
        className={`w-100% flex ${permission.includes("purchase_maker_create")
            ? "justify-between"
            : "justify-end"
          } `}
      >
        {permission.includes("purchase_maker_create") && (
          <Button
            type="button"
            icon={<span className="pi pi-plus text-sm pr-1" />}
            label="Add"
            onClick={() => {
              SetShowModel(true);
              SetModelStatus("create");
              resetForm();
            }}
            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"
            value={globalFilterValue}
            onChange={onGlobalFilterChange}
            placeholder="Search"
          />
        </span>
      </div>
    );
  };
  // Model Footer
  const renderFooter = (name) => {
    return (
      <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={() => {
              SetShowModel(false);
              reset({
                po_no: po_no,
                po_date: "",
                supplier_id: "",
                list: [],
              });
            }}
            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>
    );
  };

  const header = renderHeader();
  // Product Status section
  const statusBodyTemplate = (rowData) => {
    return (
      <b
        className={`product-badge  ${rowData.status == 1
            ? "pending"
            : rowData.status == 2
              ? "complete"
              : "new"
          } `}
      >
        {" "}
        {rowData.status == 1
          ? "pending"
          : rowData.status == 2
            ? "complete"
            : "new"}
      </b>
    );
  };
  {
    /* Data Delete Section */
  }
  const handaleDelete = (event) => {
    const id = event.currentTarget.getAttribute("data-id");
    confirmPopup({
      target: event.currentTarget,
      message: "Do you want to delete this record?",
      icon: "pi pi-info-circle",
      acceptClassName: "p-button-danger",
      accept() {
        axios
          .delete(route("purchase-makers.destroy", id))
          .then((response) => {
            setMaker(response.data.maker);
            setPoNo(response.data.po_no);
            reset({ po_no: response.data.po_no });
            toast.current.show({
              severity: "info",
              summary: "Confirmed",
              detail: response.data.success,
              life: 3000,
            });
          })
          .catch((error) => {
            toast.current.show({
              severity: "warn",
              summary: "Rejected",
              detail: error.response.data.error,
              life: 3000,
            });
          });
      },
      reject() {
        toast.current.show({
          severity: "warn",
          summary: "Rejected",
          detail: "You have rejected",
          life: 3000,
        });
      },
    });
  };
  {
    /* Data Edit  */
  }

  const HandelEdit = (element) => {
    SetShowModel(true);
    SetModelStatus("update");
    setid(element.id);
    reset({
      po_no: element.po_no,
      po_date: new Date(element.po_date),
      supplier_id: Number(element.supplier_id),
      list: element.details.map((data) => {
        return {
          product: `${data?.product_info?.name || ""}  ${data?.product_attribute?.sku
              ? ` (${data.product_attribute.sku})`
              : ""
            }`,

          product_id: Number(data.product_id),
          attribute_id: Number(data.attribute_id),
          stock_qty: auth.user.shop_id
            ? Number(
              data.product_attribute.shop_warehouse
                ? data.product_attribute.shop_warehouse
                  .quantity
                : 0
            )
            : Number(
              data.product_attribute.warehouse
                ? data.product_attribute.warehouse.quantity
                : 0
            ),
          carton_box: data.carton_box ?? "",
          quantity: data.quantity,
          price: data.price,
          total: data.total,
          other: data.product_attribute,
        };
      }),
    });
  };
  const Dublicate = (element) => {
    SetShowModel(true);
    SetModelStatus("create");
    reset({
      po_no: element.po_no,
      po_date: new Date(element.po_date),
      supplier_id: Number(element.supplier_id),
      list: element.details.map((data) => {
        return {
          product: `${data?.product_info?.name || ""}  ${data?.product_attribute?.sku
              ? ` (${data.product_attribute.sku})`
              : ""
            }`,

          product_id: Number(data.product_id),
          attribute_id: Number(data.attribute_id),
          stock_qty: auth.user.shop_id
            ? Number(
              data.product_attribute.shop_warehouse
                ? data.product_attribute.shop_warehouse
                  .quantity
                : 0
            )
            : Number(
              data.product_attribute.warehouse
                ? data.product_attribute.warehouse.quantity
                : 0
            ),
          carton_box: data.carton_box ?? "",
          quantity: data.quantity,
          price: data.price,
          total: data.total,
          other: data.product_attribute,
        };
      }),
    });
  };

  {
    /* Data Update */
  }
  const updateData = (data) => {
    axios
      .put(route("purchase-makers.update", id), data)
      .then((respose) => {
        toast.current.show({
          severity: "success",
          summary: respose.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
        SetShowModel(false);
        setMaker(respose.data.maker);
        setPoNo(respose.data.po_no);
        resetForm(respose.data.po_no);
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail: errors[field][0],
            life: 3000,
          });
        });
      });
  };
  {
    /* Date formating  */
  }
  const formatDate = (value) => {
    return value.toLocaleDateString("en-US", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

  const dateBodyTemplate = (rowData) => {
    return formatDate(new Date(rowData.po_date));
  };

  // Prient Sectioin
  const prient = (data) => {
    setPrintValue(data);
    setTimeout(() => {
      window.print();
    }, 100);
  };

  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 supplierOptionTemplate = (option) => {
    return (
      <div className="flex align-items-center">
        <div>
          {option.name} {option.number ? "(" : null}
          {option.number}
          {option.number ? ")" : null}
        </div>
      </div>
    );
  };
  //Set Seleted Product
  const selectedItem = (item) => {
    let inputValue = "";

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

      if (item.sku) inputValue += "(" + 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: inputValue,
        product_id: Number(item.product.id),
        attribute_id: Number(item.id),
        stock_qty: auth.user.shop_id
          ? Number(
            item.shop_warehouse ? item.shop_warehouse.quantity : 0
          )
          : Number(item.warehouse ? item.warehouse.quantity : 0),
        carton_box: "",
        quantity: "",
        other: item,
        price: "",
        total: 0,
      });

      setSearch((old) => {
        return {
          product: "",
        };
      });
    }
  };

  let list = watch("list");

  // Fetch low stock products
  const fetchLowStockProducts = async () => {
    setLoadingLowStock(true);
    try {
      const form = new FormData();
      form.append("company_id", null);
      form.append("product_id", null);
      form.append("brand_id", null);
      // Use shop_id if available, otherwise default to 1
      const warehouseId = auth.user?.shop_id || 1;
      form.append("warehouse_id", warehouseId);
      form.append("status", "low_stock");
      form.append("category", JSON.stringify([]));

      const response = await axios.post(
        "stock-postion-search-report",
        form
      );
      setLowStockProducts(response.data || []);
    } catch (error) {
      console.error("Error fetching low stock products:", error);
      toast.current.show({
        severity: "error",
        summary: "Error",
        detail: error.response?.data?.message || "Failed to fetch low stock products",
        life: 3000,
      });
    } finally {
      setLoadingLowStock(false);
    }
  };

  // Open low stock dialog
  const openLowStockDialog = () => {
    setLowStockDialogVisible(true);
    setSelectedLowStockProducts([]);
    fetchLowStockProducts();
  };

  // Fetch out of stock products (quantity = 0)
  const fetchOutOfStockProducts = async () => {
    setLoadingOutOfStock(true);
    try {
      const form = new FormData();
      form.append("company_id", null);
      form.append("product_id", null);
      form.append("brand_id", null);
      const warehouseId = auth.user?.shop_id || 1;
      form.append("warehouse_id", warehouseId);
      form.append("status", "out_of_stock");
      form.append("category", JSON.stringify([]));

      const response = await axios.post(
        "stock-postion-search-report",
        form
      );
      setOutOfStockProducts(response.data || []);
    } catch (error) {
      console.error("Error fetching out of stock products:", error);
      toast.current.show({
        severity: "error",
        summary: "Error",
        detail: error.response?.data?.message || "Failed to fetch out of stock products",
        life: 3000,
      });
    } finally {
      setLoadingOutOfStock(false);
    }
  };

  const openOutOfStockDialog = () => {
    setOutOfStockDialogVisible(true);
    setSelectedOutOfStockProducts([]);
    fetchOutOfStockProducts();
  };

  // Append selected low stock products to purchase order
  const appendLowStockProducts = () => {
    if (selectedLowStockProducts.length === 0) {
      toast.current.show({
        severity: "warn",
        summary: "Warning",
        detail: "Please select products to add",
        life: 3000,
      });
      return;
    }

    const currentList = watch("list");
    let addedCount = 0;
    let skippedCount = 0;

    selectedLowStockProducts.forEach((stock) => {
      const attribute = stock.attribute;
      if (!attribute) {
        skippedCount++;
        return;
      }

      // Check if product already exists
      const exists = currentList.find(
        (item) => item.attribute_id === attribute.id
      );

      if (exists) {
        skippedCount++;
        return;
      }

      const productName = attribute.product
        ? `${attribute.product.name || ""} ${attribute.sku ? `(${attribute.sku})` : ""
          }`.trim()
        : attribute.sku || "Unknown Product";

      append({
        product: productName,
        product_id: Number(attribute.product_id || attribute.product?.id || 0),
        attribute_id: Number(attribute.id),
        stock_qty: Number(stock.quantity || 0),
        carton_box: "",
        quantity: "",
        price: "",
        total: 0,
        other: attribute,
      });

      addedCount++;
    });

    if (addedCount > 0) {
      toast.current.show({
        severity: "success",
        summary: "Success",
        detail: `${addedCount} product(s) added to purchase order`,
        life: 3000,
      });
    }

    if (skippedCount > 0) {
      toast.current.show({
        severity: "warn",
        summary: "Warning",
        detail: `${skippedCount} product(s) already in the list`,
        life: 3000,
      });
    }

    setLowStockDialogVisible(false);
    setSelectedLowStockProducts([]);
  };

  const appendOutOfStockProducts = () => {
    if (selectedOutOfStockProducts.length === 0) {
      toast.current.show({
        severity: "warn",
        summary: "Warning",
        detail: "Please select products to add",
        life: 3000,
      });
      return;
    }

    const currentList = watch("list");
    let addedCount = 0;
    let skippedCount = 0;

    selectedOutOfStockProducts.forEach((stock) => {
      const attribute = stock.attribute;
      if (!attribute) {
        skippedCount++;
        return;
      }

      const exists = currentList.find(
        (item) => item.attribute_id === attribute.id
      );

      if (exists) {
        skippedCount++;
        return;
      }

      const productName = attribute.product
        ? `${attribute.product.name || ""} ${attribute.sku ? `(${attribute.sku})` : ""
          }`.trim()
        : attribute.sku || "Unknown Product";

      append({
        product: productName,
        product_id: Number(attribute.product_id || attribute.product?.id || 0),
        attribute_id: Number(attribute.id),
        stock_qty: Number(stock.quantity || 0),
        carton_box: "",
        quantity: "",
        price: "",
        total: 0,
        other: attribute,
      });

      addedCount++;
    });

    if (addedCount > 0) {
      toast.current.show({
        severity: "success",
        summary: "Success",
        detail: `${addedCount} product(s) added to purchase order`,
        life: 3000,
      });
    }

    if (skippedCount > 0) {
      toast.current.show({
        severity: "warn",
        summary: "Warning",
        detail: `${skippedCount} product(s) already in the list`,
        life: 3000,
      });
    }

    setOutOfStockDialogVisible(false);
    setSelectedOutOfStockProducts([]);
  };

  // Low stock dialog footer
  const lowStockDialogFooter = () => {
    return (
      <div className="flex justify-end gap-2">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={() => {
            setLowStockDialogVisible(false);
            setSelectedLowStockProducts([]);
          }}
          className="p-button-text"
        />
        <Button
          label="Add Selected"
          icon="pi pi-check"
          onClick={appendLowStockProducts}
          disabled={selectedLowStockProducts.length === 0}
          className="p-button-success"
        />
      </div>
    );
  };

  const outOfStockDialogFooter = () => {
    return (
      <div className="flex justify-end gap-2">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={() => {
            setOutOfStockDialogVisible(false);
            setSelectedOutOfStockProducts([]);
          }}
          className="p-button-text"
        />
        <Button
          label="Add Selected"
          icon="pi pi-check"
          onClick={appendOutOfStockProducts}
          disabled={selectedOutOfStockProducts.length === 0}
          className="p-button-success"
        />
      </div>
    );
  };

  return (
    <>
      <AuthenticatedLayout
        user={auth.user}
        header={
          <>
            <h2 className="text-skin-header font-medium ">Maker</h2>{" "}
            <p className="text-skin-sub-header font-semibold text-xs">
              {" "}
              Home - Purchase Maker
            </p>
          </>
        }
        headerButton={<></>}
      >
        <Toast ref={toast} />
        {/* View Table*/}
        <div className="card" ref={componentRef}>
          <DataTable
            className="defulattable"
            value={makers}
            paginator
            showGridlines
            rows={10}
            dataKey="id"
            header={header}
            filters={filters}
            globalFilterFields={["po_no"]}
            emptyMessage="No List found."
          >
            <Column field="po_no" header="PO No" />
            <Column
              field="po_date"
              header="PO Date"
              // filter
              // sortable
              className="w-[9rem]"
              dataType="date"
              body={dateBodyTemplate}
            // filterElement={dateFilterTemplate}
            />


            {/* <Column
                        field="total"
                        body={(data) => data.quantity + " ৳"}
                        header="Total"
                    /> */}
            <Column
              field={(data) => (
                <b>Product: {data.total_product}</b>
              )}
              header="Status"
              body={statusBodyTemplate}
            />
            <Column
              field="supplier"
              body={(data) =>
                data.supplier ? data.supplier.name : "N/A"
              }
              header="Supplier"
            />
            <Column
              header="Action"
              className="flex justify-center gap-3"
              body={(rowData) => (
                <>
                  {" "}
                  <ConfirmPopup />
                  {permission.includes(
                    "purchase_maker_edit"
                  ) &&
                    rowData.status == 0 && (
                      <Button
                        title="Edit"
                        icon="pi pi-pencil"
                        onClick={() => {
                          HandelEdit(rowData);
                        }}
                        className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                      />
                    )}
                  <Button
                    title="Duplicate"
                    icon="bx bxs-duplicate"
                    onClick={() => {
                      Dublicate(rowData);
                    }}
                    className="p-button-rounded p-button-[rgba(86,61,124,.15] mr-2 px-3 py-2  w-10 h-10 font-medium"
                  />
                  {permission.includes(
                    "purchase_maker_prient"
                  ) && (
                      <Button
                        title="Prient"
                        icon="pi pi-print"
                        onClick={() => prient(rowData)}
                        className="p-button-rounded p-button-info px-3 py-2   w-10 h-10  font-medium"
                      />
                    )}
                  {permission.includes(
                    "purchase_maker_delete"
                  ) &&
                    rowData.status == 0 && (
                      <Button
                        title="Delete"
                        icon="pi pi-trash"
                        onClick={handaleDelete}
                        data-id={rowData.id}
                        className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                      />
                    )}
                </>
              )}
              dataType="boolean"
            />
          </DataTable>
        </div>
        {/* View Table End*/}

        {/* model Section */}
        <Dialog
          header={
            modelStatus == "create"
              ? "List Maker"
              : "List Maker Update"
          }
          visible={modelshow}
          style={{ width: "90vw" }}
          footer={renderFooter("displayBasic2")}
          onHide={() => {
            SetShowModel(false);
            resetForm();
          }}
        >
          <form
            onSubmit={
              modelStatus == "create"
                ? handleSubmit(StoreData)
                : handleSubmit(updateData)
            }
            method="post"
            ref={FormSubmit}
          >
            <div className=" grid grid-cols-12 gap-6 mt-6 ">
              <div className="field col-span-3">
                <Controller
                  name="po_no"
                  rules={{
                    required: "po_no field is required",
                  }}
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <InputText
                        readOnly
                        id={field.name}
                        {...field}
                        value={
                          modelStatus == "create"
                            ? po_no
                            : field.value
                        }
                        className={
                          classNames({
                            "p-invalid":
                              fieldState.invalid,
                          }) + "w-full h-11"
                        }
                      />
                      <label htmlFor="calendar">
                        PO No
                      </label>
                    </span>
                  )}
                />
              </div>
              <div className="field col-span-3">
                <Controller
                  rules={{
                    required: "Date field is required",
                  }}
                  name="po_date"
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <Calendar
                        className="w-full h-11"
                        id="calendar"
                        inputId={field.name}
                        value={field.value}
                        onChange={(e) => {
                          field.onChange(e.value);
                        }}
                      />
                      <label htmlFor="calendar">
                        PO Date
                      </label>
                    </span>
                  )}
                />
                {errors["po_date"] ? (
                  <small className="p-error ">
                    {errors["po_date"]["message"]}
                  </small>
                ) : (
                  ""
                )}
              </div>
              <div className="field col-span-3">
                <Controller
                  name="supplier_id"
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <Dropdown
                        options={supplier}
                        value={field.value}
                        id={field.name}
                        itemTemplate={
                          supplierOptionTemplate
                        }
                        onChange={(e) => {
                          e.value
                            ? field.onChange(
                              e.value
                            )
                            : field.onChange("");
                        }}
                        optionLabel="name"
                        optionValue="id"
                        placeholder="Select Supplier"
                        showClear
                        filter
                        filterBy="name,number"
                        className="multiselect-custom w-full h-11"
                      />
                      <label htmlFor={field.name}>
                        Supplier
                      </label>
                    </span>
                  )}
                />
              </div>


              <div className="field col-span-12 md:col-span-12 mx-[25%] flex items-center gap-2">
                <div className="flex-1">
                  <Controller
                    name="product_id"
                    control={control}
                    render={({ field, fieldState }) => (
                      <StockProductDropdown
                        field={field}
                        selectedItem={selectedItem}
                      />
                    )}
                  />
                </div>
                <Button
                  label="Low Stock"
                  icon="pi pi-exclamation-triangle"
                  onClick={openLowStockDialog}
                  type="button"
                  className="p-button-warning h-11"
                  tooltip="Show low stock products"
                  tooltipOptions={{ position: "top" }}
                />
                <Button
                  label="Out of Stock"
                  icon="pi pi-box"
                  onClick={openOutOfStockDialog}
                  type="button"
                  className="p-button-danger h-11"
                  tooltip="Show out of stock products (quantity = 0)"
                  tooltipOptions={{ position: "top" }}
                />
              </div>
            </div>
            <div
              className=" grid grid-cols-12 gap-6 mt-10 "
              ref={scroll}
            >
              {fields.map((item, index) => {
                return (
                  <DynamicFieldGroup
                    key={item.id}
                    control={control}
                    watch={watch}
                    setValue={setValue}
                    remove={remove}
                    index={index}
                    getFormErrorMessageMultiple={
                      getFormErrorMessageMultiple
                    }
                    mode="purchase_maker"
                    readOnlyFields={[
                      "product_name",
                      "total",
                    ]}
                  />
                );
              })}
            </div>
            <hr />
            <div className="grid grid-cols-12 ">
              <div className="col-span-8 text-right mr-3">
                {list && (
                  <b>
                    Total QTY:{" "}
                    {list.reduce(
                      (acc, item) =>
                        acc + Number(item.quantity),
                      0
                    )}
                  </b>
                )}
              </div>
              {/* <div className="col-span-2 text-right mr-3">
                            {list && (
                                <b>
                                    Total Price:{" "}
                                    {list.reduce(
                                        (acc, item) => acc + Number(item.total),
                                        0
                                    )}
                                </b>
                            )}
                        </div> */}
            </div>
          </form>
        </Dialog>
      </AuthenticatedLayout>
      {printMode === "pos_2inch" ? (
        <PurchaseMakerPrint2Inch list={printValue} info={info} />
      ) : printMode === "pos_3inch" ? (
        <PurchaseMakerPrint3Inch list={printValue} info={info} />
      ) : (
        <PurchaseMakerPrient list={printValue} info={info} type="Purchse Order" />
      )}

      {/* Low Stock Products Dialog */}
      <Dialog
        header="Low Stock Products"
        visible={lowStockDialogVisible}
        style={{ width: "90vw", maxWidth: "1200px" }}
        footer={lowStockDialogFooter()}
        onHide={() => {
          setLowStockDialogVisible(false);
          setSelectedLowStockProducts([]);
        }}
      >
        {loadingLowStock ? (
          <div className="flex justify-center items-center py-8">
            <i className="pi pi-spin pi-spinner text-4xl text-blue-500"></i>
          </div>
        ) : (
          <DataTable
            value={lowStockProducts}
            selection={selectedLowStockProducts}
            onSelectionChange={(e) =>
              setSelectedLowStockProducts(e.value)
            }
            dataKey="id"
            paginator
            rows={10}
            rowsPerPageOptions={[10, 25, 50]}
            emptyMessage="No low stock products found"
            className="defulattable"
          >
            <Column
              selectionMode="multiple"
              headerStyle={{ width: "3rem" }}
            />
            <Column
              field="attribute.product.name"
              header="Product Name"
              sortable
              body={(rowData) => {
                const name = rowData.attribute?.product?.name || "Unknown Product";
                const attr = rowData.attribute;
                if (!attr) {
                  return <div className="font-medium text-gray-800">{name}</div>;
                }
                const getAttrValue = (a, key) => {
                  if (!a) return null;
                  const rel = a[key] || a[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())];
                  return rel?.name ?? null;
                };
                const productType = getAttrValue(attr, "product_type") || getAttrValue(attr, "productType");
                const size = getAttrValue(attr, "size");
                const color = getAttrValue(attr, "color");
                const model = getAttrValue(attr, "model");
                const goldUnit = getAttrValue(attr, "gold_unit") || getAttrValue(attr, "goldUnit");
                const goldWeight = attr.gold_weight;
                const diamondUnit = getAttrValue(attr, "diamond_unit") || getAttrValue(attr, "diamondUnit");
                const diamondWeight = attr.diamond_weight;
                const brand = getAttrValue(attr, "brand");
                const origin = getAttrValue(attr, "origin");
                const unitName = attr.unit?.name || null;
                const hasAttrs = attr.sku || unitName || productType || size || color || model || (goldUnit && goldWeight) || (diamondUnit && diamondWeight) || brand || origin;
                return (
                  <div className="min-w-0">
                    <div className="font-medium text-gray-800">{name}</div>
                    {hasAttrs && (
                      <>
                        {(attr.sku || unitName) && (
                          <div className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                            {attr.sku && (
                              <span className="text-[10px] text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-sm font-normal inline-block">
                                SKU: {attr.sku}
                              </span>
                            )}
                            {unitName && <span className="text-[10px] text-gray-500">Unit: {unitName}</span>}
                          </div>
                        )}
                        <div className="text-[10px] text-gray-600 mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                          {productType && <span>{productType}</span>}
                          {size && <span>• {size}</span>}
                          {color && <span>• {color}</span>}
                          {model && <span>• {model}</span>}
                          {goldUnit && goldWeight && (
                            <span className="text-amber-700">• Gold <b>{goldWeight}</b> {goldUnit}</span>
                          )}
                          {diamondUnit && diamondWeight && (
                            <span className="text-blue-700">• Dia <b>{diamondWeight}</b> {diamondUnit}</span>
                          )}
                          {brand && <span className="text-gray-500">• {brand}</span>}
                          {origin && <span>• Origin: {origin}</span>}
                        </div>
                      </>
                    )}
                  </div>
                );
              }}
            />
            <Column
              field="attribute.sku"
              header="SKU"
              sortable
            />
            <Column
              field="quantity"
              header="Current Stock"
              sortable
              body={(rowData) => (
                <span className="text-red-600 font-semibold">
                  {rowData.quantity || 0}
                </span>
              )}
            />
            <Column
              field="attribute.stock_alert"
              header="Alert Level"
              sortable
              body={(rowData) =>
                rowData.attribute?.stock_alert || "-"
              }
            />
            <Column
              field="warehouse.name"
              header="Warehouse"
              sortable
              body={(rowData) =>
                rowData.warehouse?.name || "-"
              }
            />
          </DataTable>
        )}
      </Dialog>

      {/* Out of Stock Products Dialog */}
      <Dialog
        header="Out of Stock Products"
        visible={outOfStockDialogVisible}
        style={{ width: "90vw", maxWidth: "1200px" }}
        footer={outOfStockDialogFooter()}
        onHide={() => {
          setOutOfStockDialogVisible(false);
          setSelectedOutOfStockProducts([]);
        }}
      >
        {loadingOutOfStock ? (
          <div className="flex justify-center items-center py-8">
            <i className="pi pi-spin pi-spinner text-4xl text-blue-500"></i>
          </div>
        ) : (
          <DataTable
            value={outOfStockProducts}
            selection={selectedOutOfStockProducts}
            onSelectionChange={(e) =>
              setSelectedOutOfStockProducts(e.value)
            }
            dataKey="id"
            paginator
            rows={10}
            rowsPerPageOptions={[10, 25, 50]}
            emptyMessage="No out of stock products found"
            className="defulattable"
          >
            <Column
              selectionMode="multiple"
              headerStyle={{ width: "3rem" }}
            />
            <Column
              field="attribute.product.name"
              header="Product Name"
              sortable
              body={(rowData) => {
                const name = rowData.attribute?.product?.name || "Unknown Product";
                const attr = rowData.attribute;
                if (!attr) {
                  return <div className="font-medium text-gray-800">{name}</div>;
                }
                const getAttrValue = (a, key) => {
                  if (!a) return null;
                  const rel = a[key] || a[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())];
                  return rel?.name ?? null;
                };
                const productType = getAttrValue(attr, "product_type") || getAttrValue(attr, "productType");
                const size = getAttrValue(attr, "size");
                const color = getAttrValue(attr, "color");
                const model = getAttrValue(attr, "model");
                const goldUnit = getAttrValue(attr, "gold_unit") || getAttrValue(attr, "goldUnit");
                const goldWeight = attr.gold_weight;
                const diamondUnit = getAttrValue(attr, "diamond_unit") || getAttrValue(attr, "diamondUnit");
                const diamondWeight = attr.diamond_weight;
                const brand = getAttrValue(attr, "brand");
                const origin = getAttrValue(attr, "origin");
                const unitName = attr.unit?.name || null;
                const hasAttrs = attr.sku || unitName || productType || size || color || model || (goldUnit && goldWeight) || (diamondUnit && diamondWeight) || brand || origin;
                return (
                  <div className="min-w-0">
                    <div className="font-medium text-gray-800">{name}</div>
                    {hasAttrs && (
                      <>
                        {(attr.sku || unitName) && (
                          <div className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                            {attr.sku && (
                              <span className="text-[10px] text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-sm font-normal inline-block">
                                SKU: {attr.sku}
                              </span>
                            )}
                            {unitName && <span className="text-[10px] text-gray-500">Unit: {unitName}</span>}
                          </div>
                        )}
                        <div className="text-[10px] text-gray-600 mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                          {productType && <span>{productType}</span>}
                          {size && <span>• {size}</span>}
                          {color && <span>• {color}</span>}
                          {model && <span>• {model}</span>}
                          {goldUnit && goldWeight && (
                            <span className="text-amber-700">• Gold <b>{goldWeight}</b> {goldUnit}</span>
                          )}
                          {diamondUnit && diamondWeight && (
                            <span className="text-blue-700">• Dia <b>{diamondWeight}</b> {diamondUnit}</span>
                          )}
                          {brand && <span className="text-gray-500">• {brand}</span>}
                          {origin && <span>• Origin: {origin}</span>}
                        </div>
                      </>
                    )}
                  </div>
                );
              }}
            />
            <Column
              field="attribute.sku"
              header="SKU"
              sortable
            />
            <Column
              field="quantity"
              header="Current Stock"
              sortable
              body={(rowData) => (
                <span className="text-red-600 font-semibold">
                  {rowData.quantity || 0}
                </span>
              )}
            />
            <Column
              field="attribute.stock_alert"
              header="Alert Level"
              sortable
              body={(rowData) =>
                rowData.attribute?.stock_alert || "-"
              }
            />
            <Column
              field="warehouse.name"
              header="Warehouse"
              sortable
              body={(rowData) =>
                rowData.warehouse?.name || "-"
              }
            />
          </DataTable>
        )}
      </Dialog>
    </>
  );
}

export default PurchaseMaker;
