import { React, useState, useContext } from "react";

import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { useRef } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { authUser } from "@/Components/AuthProvider";
import jsPDF from "jspdf";
import { AutoComplete } from "primereact/autocomplete";
import { Dropdown } from "primereact/dropdown";

import { renderPDF } from "@/Utils/helper";
import { MultiSelect } from "primereact/multiselect";
import ProductDropdown from "@/Components/ProductDropdown";
function ProductInfo({ auth, products, warehouseList }) {
    const { permission, category } = useContext(authUser);
    const [size, setsize] = useState([]);
    const [model, setmodel] = useState([]);
    const [brand, setbrand] = useState([]);
    const [sizeId, setsizeId] = useState(null);
    const [productId, setProductId] = useState(null);
    const [modelId, setmodelId] = useState(null);
    const [brandId, setbrandId] = useState(null);
    const [product, setProduct] = useState([]);
    const toast = useRef(null);
    const [warehouse, setWarehouse] = useState([]);
    const [selectedCategory, setCategory] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [searchValue, setSearchValue] = useState({
        product: "",
        size: "",
        model: "",
        brand: "",
    });

    useEffect(() => {
        if (!permission.includes("report_super_admin_access")) {
            setWarehouse(auth.user.shop_id);
        }
    }, []);

    const search = async () => {
        setIsLoading(true);
        let form = new FormData();
        form.append("size_id", sizeId);
        form.append("product_id", productId);
        form.append("model_id", modelId);
        form.append("brand_id", brandId);
        form.append("form_warehouse_id", warehouse);
        form.append("category", JSON.stringify(selectedCategory));
        const response = await axios.post("current-product", form);
        return response.data;
    };

    const filtersize = (event) => {
        setTimeout(() => {
            axios
                .post(route("size.search"), { data: event.query })
                .then((response) => {
                    setsize(response.data);
                });
        }, 250);
    };

    const filtermodel = (event) => {
        setTimeout(() => {
            axios
                .post(route("model.search"), {
                    data: event.query,
                })
                .then((response) => {
                    setmodel(response.data);
                });
        }, 250);
    };
    const brandModel = (event) => {
        setTimeout(() => {
            axios
                .post(route("brand.search"), {
                    data: event.query,
                })
                .then((response) => {
                    setbrand(response.data);
                });
        }, 250);
    };

    const sizeTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>{option.name}</div>
            </div>
        );
    };
    const modelTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>{option.name}</div>
            </div>
        );
    };
    const brandTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>{option.name}</div>
            </div>
        );
    };

    const openInNewTab = async () => {
        const data = await search();
        const pdfDoc = await window.generatePDFView(
            data,
            window.reportModes.productInfo,
            false,
            "Product Overview"
        );
        renderPDF(pdfDoc, "ProductInfo.pdf");
        setIsLoading(false);
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Product Info
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - ProductInfo
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card min-h-screen">
                <div className="bg-gray-100  flex items-center justify-center py-12 px-2 sm:px-6 lg:px-8">
                    <div className="w-full max-w-5xl bg-white rounded-2xl shadow-lg border border-gray-200 p-4 sm:p-8 md:p-10">
                        <h2 className="text-2xl md:text-3xl font-bold text-center text-gray-800 mb-8 md:mb-10 tracking-tight">
                            Filter Report Criteria
                        </h2>
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                            {/* Product */}
                            <div>
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Product
                                </label>
                                <ProductDropdown
                                    // field={{name: "product"}}
                                    reportMode={true}
                                    selectedItem={(e) => {
                                        if (e?.id) {
                                            setProductId(e.id);
                                        } else {
                                            setProductId(null);
                                        }
                                    }}
                                />
                            </div>

                            {/* Size */}
                            {[1, 2, 3, 4, 5, 6].includes(
                                window?.setting?.business_id
                            ) && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-600 mb-2">
                                        Size
                                    </label>
                                    <AutoComplete
                                        value={searchValue.size}
                                        suggestions={size}
                                        completeMethod={filtersize}
                                        itemTemplate={sizeTemplateIOptionList}
                                        onChange={(e) => {
                                            e.value?.name
                                                ? setsizeId(e.value.id)
                                                : setsizeId(null);
                                            setSearchValue((old) => ({
                                                ...old,
                                                size: e.value.name || e.value,
                                            }));
                                        }}
                                        className="w-full rounded-lg shadow-sm focus:ring-2 focus:ring-blue-300"
                                        dropdown
                                    />
                                </div>
                            )}

                            {/* Model */}
                            {[1, 2, 3, 4, 5].includes(
                                window?.setting?.business_id
                            ) && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-600 mb-2">
                                        Model
                                    </label>
                                    <AutoComplete
                                        value={searchValue.model}
                                        suggestions={model}
                                        completeMethod={filtermodel}
                                        itemTemplate={modelTemplateIOptionList}
                                        onChange={(e) => {
                                            e.value?.name
                                                ? setmodelId(e.value.id)
                                                : setmodelId(null);
                                            setSearchValue((old) => ({
                                                ...old,
                                                model: e.value.name || e.value,
                                            }));
                                        }}
                                        className="w-full rounded-lg shadow-sm focus:ring-2 focus:ring-blue-300"
                                        dropdown
                                    />
                                </div>
                            )}

                            {/* Category */}
                            <div>
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Select Category
                                </label>
                                <MultiSelect
                                    value={selectedCategory}
                                    options={category}
                                    optionLabel="name"
                                    optionValue="id"
                                    placeholder="Select Category"
                                    onChange={(e) => setCategory(e.value)}
                                    className="w-full rounded-lg shadow-sm focus:ring-2 focus:ring-blue-300"
                                />
                            </div>
                            {/* Brand */}
                            {[1, 2, 3, 4, 5].includes(
                                window?.setting?.business_id
                            ) && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-600 mb-2">
                                        Brand
                                    </label>
                                    <AutoComplete
                                        value={searchValue.brand}
                                        suggestions={brand}
                                        completeMethod={brandModel}
                                        itemTemplate={brandTemplateIOptionList}
                                        onChange={(e) => {
                                            e.value?.name
                                                ? setbrandId(e.value.id)
                                                : setbrandId(null);
                                            setSearchValue((old) => ({
                                                ...old,
                                                brand: e.value.name || e.value,
                                            }));
                                        }}
                                        className="w-full rounded-lg shadow-sm focus:ring-2 focus:ring-blue-300"
                                        dropdown
                                    />
                                </div>
                            )}

                            {/* Warehouse (conditionally rendered) */}

                            {permission.includes(
                                "report_super_admin_access"
                            ) && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-600 mb-2">
                                        Warehouse/Shop
                                    </label>
                                    <Dropdown
                                        value={warehouse}
                                        options={warehouseList}
                                        optionLabel="name"
                                        optionValue="id"
                                        placeholder="Select a Warehouse"
                                        showClear
                                        disabled={
                                            !permission.includes(
                                                "report_super_admin_access"
                                            )
                                        }
                                        onChange={(e) =>
                                            setWarehouse(e.target.value ?? null)
                                        }
                                        className="w-full rounded-lg shadow-sm"
                                        inputClassName="h-11 px-4 text-sm"
                                    />
                                </div>
                            )}
                        </div>
                        {/* Submit Button */}
                        <div className="mt-10 flex justify-center">
                            <button
                                type="button"
                                onClick={openInNewTab}
                                disabled={isLoading}
                                className={`px-6 py-3 rounded-xl font-semibold text-sm min-w-[160px] flex items-center justify-center gap-2 transition duration-200
                    ${
                        isLoading
                            ? "bg-blue-400 cursor-not-allowed"
                            : "bg-blue-600 hover:bg-blue-700"
                    }
                    text-white shadow-md`}
                            >
                                {isLoading ? (
                                    <>
                                        <span
                                            className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"
                                            aria-hidden="true"
                                        />
                                        <span className="text-xs font-medium">
                                            Generating...
                                        </span>
                                    </>
                                ) : (
                                    <>
                                        <span
                                            role="img"
                                            aria-label="View Report"
                                        >
                                            🔍
                                        </span>
                                        View Report
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

export default ProductInfo;
