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 html2canvas from "html2canvas";
import jsPDF from "jspdf";
import ReportHeading from "@/Components/ReportHeading";
import ReportInfo from "@/Components/ReportInfo";
import { renderPDF } from "@/Utils/helper";

function PurchaseSummary({ auth }) {
    const { permission, warehouseList,supplierList} = useContext(authUser);
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [purchase, setPurchase] = useState([]);
    const [supplier, setSupplier] = useState([]);
    const toast = useRef(null);
    const doc = new jsPDF();
    const [location, setLocation] = useState([]);
    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("location_id", location);
        form.append("supplier", supplier);
        let res = await axios.post("purchase-report-search", form);
        return res.data;
    };

    const openInNewTab = async () => {
        const data = await search();
        const pdfDoc = await window.generatePDFView(
            data,
            window.reportModes.purchaseSummary,
            false,
            "Purchase Summary",
            startDate,
            endDate
        );
        renderPDF(pdfDoc, "purchaseSummary.pdf");
        setIsLoading(false);
    };

    const purchaseFiltered = {};
    purchase.forEach((item) => {
        if (purchaseFiltered[item.date]) {
            purchaseFiltered[item.date].invoice += Number(item.invoice_count);
            purchaseFiltered[item.date].details = purchaseFiltered[
                item.date
            ].details.concat(item.purchase_detalis);
            purchaseFiltered[item.date].total += Number(item.total);
        } else {
            purchaseFiltered[item.date] = {
                invoice: Number(item.invoice_count),
                details: item.purchase_detalis,
                total: Number(item.total),
            };
        }
    });

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Purchase Summary
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - PurchaseSummary
                    </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">
                            {/* Starting Date */}
                            <div className="col-span-12 md: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>
                            {/* End Date */}
                            <div className="col-span-12 md: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 */}
                            <div className="col-span-12 sm:col-span-4">
                                <label className="block text-sm font-medium text-gray-600 mb-2">
                                    Supplier
                                </label>
                                <Dropdown
                                    value={supplier} // Make sure this is the state you are updating
                                    options={supplierList}
                                    optionLabel="name"
                                    optionValue="id"
                                    placeholder="Select a Supplier"
                                    showClear
                                    onChange={(e) =>
                                        setSupplier(e.value ?? null)
                                    } // Use e.value instead of e.target.value
                                    className="w-full rounded-lg shadow-sm"
                                    inputClassName="h-11 px-4 text-sm"
                                />
                            </div>
                            {/* Warehouse/Shop */}
                            {permission.includes(
                                "report_super_admin_access"
                            ) && (
                                <div className="col-span-12 md:col-span-4">
                                    <label className="block text-sm font-medium text-gray-600 mb-2">
                                        Warehouse/Shop
                                    </label>
                                    <Dropdown
                                        value={location}
                                        options={warehouseList}
                                        optionLabel="name"
                                        optionValue="id"
                                        placeholder="Select a Warehouse"
                                        showClear
                                        disabled={
                                            !permission.includes(
                                                "report_super_admin_access"
                                            )
                                        }
                                        onChange={(e) =>
                                            setLocation(e.target.value ?? null)
                                        }
                                        className="w-full rounded-lg shadow-sm"
                                        inputClassName="h-11 px-4 text-sm"
                                    />
                                </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 PurchaseSummary;
