import { React, useState, useContext, useEffect } 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 { AutoComplete } from "primereact/autocomplete";
import { authUser } from "@/Components/AuthProvider";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { renderPDF } from "@/Utils/helper";
import { BlobProvider } from "@react-pdf/renderer";
import SalesPersonSalaryStatementPDF from "@/Components/SalesPersonSalaryStatementPDF";
import SalesPersonSearch from "@/Components/SalesPersonSearch";
import { useForm } from "react-hook-form";
function SalesPersonSalary({ auth }) {
    const { permission, warehouseList } = useContext(authUser);
    const [salesPersonDisplayText, setSalesPersonDisplayText] = useState("");
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const toast = useRef(null);
    const [salesPersonId, setSalesPersonId] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [searchData, setSearchData] = useState({});

    const pdfUrlRef = useRef(null);

    const { register, control } = useForm({});
    const search = async () => {
        setIsLoading(true);
        let form = new FormData();
        form.append("startMonth", startDate);
        form.append("endDate", endDate);
        form.append("salesPerson", salesPersonId);

        let res = await axios.post("sales-person-salary-report-show", form);
        setSearchData(res.data);
        return res.data;
    };
    const openInNewTab = async () => {
        await search();
        setTimeout(() => {
            if (pdfUrlRef.current) {
                window.open(pdfUrlRef.current, "_blank", "noopener,noreferrer");
            }
            setIsLoading(false);
        }, 300);

        // const data = await search();
        // const pdfDoc = await window.generatePDFView(
        //     data,
        //     window.reportModes.supplierPayment,
        //     false,
        //     "Supplier Payment Details",
        //     startDate,
        //     endDate
        // );
        // renderPDF(pdfDoc, "Supplier Payment .pdf");
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Sales Person Salary Report
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Sales Person Salary Report
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card p-5">
                <div className="min-h-screen  bg-gray-100  py-12 px-4 sm:px-6 lg:px-8">
                    <div className="max-w-5xl mx-auto bg-white rounded-2xl shadow-lg p-10 border border-gray-200">
                        <h2 className="text-3xl font-bold text-center text-gray-800 mb-10 tracking-tight">
                            Filter Report Criteria
                        </h2>
                        <div className="grid  grid-cols-12  gap-6">
                            <div className="col-span-12 md:col-span-4">
                                <label htmlFor="type">Starting Date</label>
                                <Calendar
                                    value={startDate}
                                    onChange={(e) => setStartDate(e.value)}
                                    showIcon // optional: calendar icon
                                    className="h-[41px] text-[14px]"
                                />
                            </div>
                            <div className="col-span-12 md:col-span-4">
                                <label htmlFor="type">End Date</label>
                                <Calendar
                                    value={endDate}
                                    onChange={(e) => setEndDate(e.value)}
                                    showIcon
                                    className="h-[41px] text-[14px]"
                                />
                            </div>

                            <div className="col-span-12 sm:col-span-4">
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Search Sales Person
                                </label>
                                <SalesPersonSearch
                                    control={control}
                                    salesPersonText={salesPersonDisplayText}
                                    onSalesPersonSelect={(selectedPerson) => {
                                        setSalesPersonId(selectedPerson.id);
                                    }}
                                    placeholder="Search Sales Person"
                                    className="w-full h-11"
                                />
                            </div>
                        </div>

                        <BlobProvider
                            document={
                                <SalesPersonSalaryStatementPDF
                                    searchData={searchData}
                                />
                            }
                        >
                            {({ url, loading }) => {
                                if (!loading) {
                                    pdfUrlRef.current = url;
                                }
                                return null; // don't render link
                            }}
                        </BlobProvider>
                        <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 SalesPersonSalary;
