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

import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";

import { useRef } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";

import { authUser } from "@/Components/AuthProvider";
import { Dropdown } from "primereact/dropdown";
import { Calendar } from "primereact/calendar";

import jsPDF from "jspdf";
import ProductDropdown from "@/Components/ProductDropdown";
import CustomerDropdown from "@/Components/CustomerDropdown";
import { renderPDF } from "@/Utils/helper";
import { useReactToPrint } from "react-to-print";
function SalseDetailsReport({ auth }) {
    const { permission, warehouseList } = useContext(authUser);
    const [type, setType] = useState("All");
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [salse, setSales] = useState([]);
    const [details, setDetails] = useState([]);
    const [shop, setShop] = useState([]);
    const conponentPDF = useRef();
    const [location, setLocation] = useState([]);
    const [customerId, setCustomerID] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [productId, setProductId] = useState(false);

    const toast = useRef(null);
    const doc = new jsPDF();
    const [supplier, setSupplier] = useState([]);
    const [supplierId, setSupplierID] = useState(null);
    const [prientHeader, setPrintHeader] = useState(false);
    useEffect(() => {
        axios.get(route("sales.report.shop")).then((res) => {
            setShop(res.data.shop);
        });
        if (!permission.includes("report_super_admin_access")) {
            setLocation(auth.user.shop_id);
        }
    }, []);

    const search = async () => {
        setIsLoading(true);
        let form = new FormData();
        form.append("type", type);
        form.append("start", startDate);
        form.append("end", endDate);
        form.append("supplier_id", supplierId);
        form.append("customer_id", customerId);
        form.append("location_id", location);
        form.append("attribute_id", productId);
        let res = await axios.post("salseSearchDetails", form);

        return res.data;
    };
    const openInNewTab = async () => {
        const data = await search();
        const pdfDoc = await window.generatePDFView(
            data.salesInfo,
            window.reportModes.saleDetails,
            false,
            "Sale Details",
            startDate,
            endDate,
            data.discount
        );
        renderPDF(pdfDoc, "saleDetails.pdf");
        setIsLoading(false);
    };
    const exportPDF = useReactToPrint({
        content: () => conponentPDF.current,
        onAfterPrint: () => {
            setPrintHeader(false);
        },
    });
    const startDateText = `Start Date: ${new Date(startDate).toLocaleDateString(
        "en-US"
    )}`;
    const endDateText = endDate
        ? `to End Date: ${new Date(endDate).toLocaleDateString("en-US")}`
        : "";
    const dateText = endDate
        ? `${startDateText} ${endDateText}`
        : startDateText;

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

    let total = 0;

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Salse Details Report
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - SalseDetailsReport
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card  min-h-screen">
                <div className="bg-gray-100  flex items-center justify-center py-8 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 md:gap-6">
                            {/* Starting Date */}
                            <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>

                            {/* End Date */}
                            <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>

                            {/* Search Product */}
                            <div className="col-span-12 sm:col-span-4">
                                <label
                                    htmlFor="type"
                                    className="block text-sm font-medium text-gray-600 mb-2"
                                >
                                    Search Product
                                </label>
                                <ProductDropdown
                                    // field={{name: "product"}}
                                    reportMode={true}
                                    selectedItem={(e) => {
                                        if (e?.id) {
                                            setProductId(e.id);
                                        } else {
                                            setProductId(null);
                                        }
                                    }}
                                />
                            </div>

                            {/* Customer/Retailer */}
                            <div className="col-span-12 sm:col-span-4">
                                <CustomerDropdown
                                    onSelect={(customer) => setCustomerID(customer.id)}
                                    className="w-full"
                                    inputClassName="w-full h-10 rounded-lg"
                                />
                            </div>

                            {/* Warehouse/Shop */}
                            {permission.includes(
                                "report_super_admin_access"
                            ) && (
                                <div className="col-span-12 sm: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 SalseDetailsReport;
