import { React, useState } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { InputText } from "primereact/inputtext";
import { useRef } from "react";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { FilterMatchMode, FilterOperator } from "primereact/api";
import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";
import BarcodeReader from "react-barcode";
import { useReactToPrint } from "react-to-print";
import { classNames } from "primereact/utils";

function Barcode({ auth }) {
    const { permission } = useContext(authUser);
    const [searchStatus, SetsearchStatus] = useState("");
    const [searchAbleItem, SetsearchAbleItem] = useState([]);
    const [lablePritenQty, SetLablePritenQty] = useState([]);
    const [preview, SetPreview] = useState(false);
    const componentRef = useRef();
    const toast = useRef(null);
    const [filters, setFilters] = useState({
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
        type: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    });
    const [globalFilterValue, setGlobalFilterValue] = useState("");

    const {
        register,
        control,
        handleSubmit,
        formState: { errors },
        watch,
        reset,
        setValue,
    } = useForm({
        list: [
            {
                product_label: "",
                product_name: "",
                product_id: "",
                attribute_id: "",
                quantity: "",
                purchase: "",
                salse: "",
                total: 0,
                lavel: 0,
            },
        ],
    });

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

    //Product Search
    // Call this once and store the returned handler on your input’s onChange / @input
    const searchProduct  = (() => {
        let timerId; // private to the returned function
        const DELAY = 300; // debounce delay (ms) – tweak if you like

        return (e) => {
            clearTimeout(timerId); // reset any earlier keystroke
            timerId = setTimeout(() => {
                const value = e.target.value.trim();

                if (value.length) {
                    axios
                        .post(route("purchase.product.search.barcode"), {
                            data: value,
                        })
                        .then(({ data }) => {
                            SetsearchAbleItem(data.produts);
                            SetsearchStatus(data.produts.length === 0);
                        })
                        .catch(() => {
                            SetsearchAbleItem([]);
                            SetsearchStatus(true);
                        });
                } else {
                    SetsearchAbleItem([]);
                    SetsearchStatus(false);
                }
            }, DELAY);
        };
    })();

    const handlePrint = useReactToPrint({
        content: () => componentRef.current,
    });

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">Barcode</h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Barcode
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            <div className="field col-span-12  mx-[20%] relative  ">
                <Controller
                    name="search_item"
                    control={control}
                    render={({ field, fieldState }) => (
                        <span className="p-float-label">
                            <InputText
                                id={field.name}
                                {...field}
                                onKeyUp={searchProduct }
                                className={
                                    classNames({
                                        "p-invalid": fieldState.invalid,
                                    }) + "w-[100%] h-11 border border-zinc-950"
                                }
                            />
                            <label htmlFor={field.name}>Product Name/SKU</label>
                        </span>
                    )}
                />

                <div className="bg-[#f1f6ed] h-70 shadow-xl divide-y divide-gray-300 absolute w-full z-10  ">
                    {searchAbleItem && searchAbleItem.length != 0 ? (
                        <>
                            {searchAbleItem.map((item) => {
                                return (
                                    <div
                                        onClick={(e) => {
                                            // Assuming "inputField" is the reference to your input field
                                            let inputValue = "";
                                            let inputlabel = "";
                                            // Construct the concatenated string
                                            if (item.product) {
                                                inputlabel +=
                                                    "Categroy: " +
                                                    item.product.category.name +
                                                    " --> ";

                                                if (item.unit)
                                                    inputlabel +=
                                                        "Unit: " +
                                                        item.unit.name +
                                                        " --> ";
                                                if (item.color)
                                                    inputlabel +=
                                                        "Color: " +
                                                        item.color.name +
                                                        " --> ";
                                                if (item.brand)
                                                    inputlabel +=
                                                        "Brand: " +
                                                        item.brand.name;
                                            }

                                            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 alrady add ",
                                                    life: 3000,
                                                });
                                            } else {
                                                append({
                                                    product_label: inputlabel,
                                                    product_name: inputValue,
                                                    product_id: Number(
                                                        item.product.id
                                                    ),
                                                    attribute_id: Number(
                                                        item.id
                                                    ),
                                                    quantity: "",
                                                    purchase: "",
                                                    lavel: item.barcode,
                                                    price:
                                                        item?.shop_warehouse
                                                            ?.salse ?? null,
                                                    name:
                                                        item?.product?.name ??
                                                        null,
                                                    sku: item?.sku ?? null,
                                                });
                                            }

                                            SetsearchAbleItem([]);
                                            SetsearchStatus(false);
                                        }}
                                        className=" flex justify-between text-[12px] cursor-pointer   p-3  hover:bg-[#176DE8] hover:text-white"
                                    >
                                        <p className="text-[16px]">
                                            Category:{" "}
                                            {item.product &&
                                                item.product.category.name}
                                            {"-->"}
                                            Name:{" "}
                                            {item.product &&
                                                item.product.name + "-->"}
                                            {item.sku &&
                                                "SKU: " + item.sku + "-->"}
                                            {item.unit &&
                                                "Unit: " +
                                                    item.unit.name +
                                                    "-->"}
                                            {item.color &&
                                                "Color: " +
                                                    item.color.name +
                                                    "-->"}
                                            {item.brand &&
                                                "Brand: " + item.brand.name}
                                        </p>
                                    </div>
                                );
                            })}
                        </>
                    ) : (
                        <>
                            {searchStatus ? (
                                <p className="text-center text-[12px] p-3">
                                    Data not found
                                </p>
                            ) : (
                                ""
                            )}
                        </>
                    )}
                </div>
            </div>
            <div className="relative  mt-5">
                <table className="w-full text-sm text-left rtl:text-right text-gray-500 border-collapse border">
                    <thead className="text-xs text-gray-700 uppercase bg-gray-50 ">
                        <tr>
                            <th scope="col" className="px-6 py-3 border ">
                                Item Name
                            </th>

                            <th scope="col" className="px-6 py-3 border">
                                Action
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        {fields.map((item, index) => {
                            return (
                                <tr className="bg-white border-b ">
                                    <th
                                        scope="row"
                                        className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap"
                                    >
                                        {item.product_name}
                                    </th>

                                    <td className="px-6 py-4 border flex gap-3">
                                        <button
                                            onClick={() => {
                                                remove(index);
                                                SetPreview(false);

                                                let get = lablePritenQty.filter(
                                                    (e) => e[1] != item.lavel
                                                );

                                                SetLablePritenQty(get);
                                            }}
                                            className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
                                        >
                                            -
                                        </button>

                                        <a
                                            target="_blank"
                                            href={`label/print/${item.attribute_id}`}
                                        >
                                            Label Print
                                        </a>
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        </AuthenticatedLayout>
    );
}

export default Barcode;
