import { React, useState, useContext } from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
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 { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { authUser } from "@/Components/AuthProvider";
import { Dropdown } from "primereact/dropdown";
import { Calendar } from "primereact/calendar";
import { renderPDF } from "@/Utils/helper";
import { AutoComplete } from "primereact/autocomplete";
import jsPDF from "jspdf";

function SupplierLedgerReport({ auth }) {
    const { permission, warehouseList } = useContext(authUser);
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [location, setLocation] = useState([]);
    const [supplier, setSupplier] = useState([]);
    const [supplierId, setSupplierId] = useState(null);
    const toast = useRef(null);
    const [searchSupplier, setSearchValue] = useState({
        supplier: "",
    });
    const [isLoading, setIsLoading] = useState(false);
    useEffect(() => {
        if (!permission.includes("report_super_admin_access")) {
            setLocation(auth.user.shop_id);
        }
    }, []);

    const search = async () => {
        setIsLoading(true);
        let form = new FormData();
        form.append("start", startDate);
        form.append("end", endDate);
        form.append("supplier_id", supplierId);
        let res = await axios.post("supplier-ledger-report-search", form);
        return res.data;
    };

    const openInNewTab = async () => {
        const data = await search();
        const pdfDoc = await window.generatePDFView(
            data?.supplierLedger,
            window.reportModes.supplierLedger,
            data?.supplier,
            "Supplier Ledger Report",
            startDate,
            endDate
        );
        renderPDF(pdfDoc, "Supplier Ledger Report .pdf");
        setIsLoading(false);
    };

    const filtersupplier = (event) => {
        setTimeout(() => {
            axios
                .post(route("supplier.search"), { data: event.query })
                .then((response) => {
                    setSupplier(response.data);
                });
        }, 250);
    };

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

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Supplier Ledger Report
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Report - Supplier Ledger Report
                    </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-12 gap-6">
                            <div className="col-span-12 sm:col-span-4">
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Starting Date
                                </label>
                                <Calendar
                                    value={startDate}
                                    onChange={(e) => setStartDate(e.value)}
                                    className="w-full h-[41px] text-[14px] rounded-lg shadow-sm"
                                />
                            </div>
                            <div className="col-span-12 sm:col-span-4">
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    End Date
                                </label>
                                <Calendar
                                    value={endDate}
                                    onChange={(e) => setEndDate(e.value)}
                                    className="w-full h-[41px] text-[14px] rounded-lg shadow-sm"
                                />
                            </div>

                            {/* supplier/Retailer */}
                            <div className="col-span-12 sm:col-span-4">
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Search Supplier
                                </label>
                                <AutoComplete
                                    value={searchSupplier.supplier}
                                    suggestions={supplier}
                                    completeMethod={filtersupplier}
                                    aria-label="supplier_id"
                                    dropdown
                                    itemTemplate={supplierTemplateIOptionList}
                                    onChange={(e) => {
                                        if (e.value.name) {
                                            setSupplierId(e.value.id);
                                        } else {
                                            setSupplierId(null);
                                        }
                                        setSearchValue((old) => ({
                                            ...old,
                                            supplier: e.value.name
                                                ? `${e.value.name}`
                                                : e.value,
                                        }));
                                    }}
                                    dropdownAriaLabel="Select supplier"
                                    className="w-full h-10 rounded-lg"
                                />
                            </div>
                        </div>
                        <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 SupplierLedgerReport;
