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

function SalseRetutnReport({ auth }) {
    const { permission } = useContext(authUser);
    const [type, setType] = useState("All");
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();

    const [salesReturn, setSalesReturn] = useState([]);
    const [shop, setShop] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const conponentPDF = useRef();
    const toast = useRef(null);
    const doc = new jsPDF();

    const search =async () => {
        setIsLoading(true);
        let form = new FormData();
        form.append("start", startDate);
        form.append("end", endDate);
     let res= await  axios.post("sales-return-search", form);
         return res.data;
       
    };
    const openInNewTab = async () => {
            const data = await search();
      
            
            const pdfDoc = await window.generatePDFView(
                data,
                window.reportModes.salesReturn,
                false,

                  "Sales Return Report",
                startDate,
                endDate,
              
            );
            renderPDF(pdfDoc, "salesReturnReport.pdf");
            setIsLoading(false);
        };
    const exportPDF = () => {
        const cols = [
            { field: "index", header: "SI" },
            { field: "invoice_no", header: "Invoice No" },
            { field: "client_name", header: "Customer/Retailer Name" },
            { field: "product_name", header: "Product" },
            { field: "return_qty", header: "Return Qty" },
            { field: "return_price", header: "Return Price" },
            { field: "value", header: "Value" },
        ];
        const exportColumns = cols.map((col) => ({
            title: col.header,
            dataKey: col.field,
        }));

        import("jspdf").then((jsPDF) => {
            import("jspdf-autotable").then(() => {
                const doc = new jsPDF.default("l", "mm", "a4");
                const pageWidth = doc.internal.pageSize.getWidth();
                const companyName = "Unity";
                // Add a title or header above the table
                doc.setFontSize(15);
                doc.setFont("Arial", "bold");
                const CompanyTotallength = doc.getTextWidth(companyName);
                doc.text(companyName, (pageWidth - CompanyTotallength) / 2, 20); // Position the header at (x, y)

                let reportTitle = "Sales Return Rep";
                const reportTotallength = doc.getTextWidth(reportTitle);
                doc.setFontSize(12);
                doc.setFont("Arial", "bold");
                doc.text(
                    "Sales Return Report",
                    (pageWidth - reportTotallength) / 2,
                    27
                );

                // Add start date and end date

                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 dateTextWidth = doc.getTextWidth(dateText);
                doc.setFontSize(10);
                doc.setFont("Arial", "normal");
                doc.text(dateText, (pageWidth + 14 - dateTextWidth) / 2, 33);

                const formattedData = salesReturn.flatMap((item, index) => {
                    return item.details.map((detail) => {

                        return {
                            index: index + 1, // Add index for each detail entry
                            invoice_no: item.reference_no,

                            client_name: (item.client?.name ?? "N/A") + " (" + (item.client?.code ?? "N/A") + ')',
                            product_name: detail.product.name + (detail.attribute && "(" + detail.attribute.sku + ")"),
                            return_qty: detail.return_qty,
                            return_price: detail.return_price,
                            value: detail.total,

                            rowSpan: item.details.length,
                        };
                    });
                });

                // Customize header styles
                const headStyles = {
                    fillColor: [69, 69, 69], // Background color (RGB)
                    textColor: [255, 255, 255], // Text color (RGB)
                    fontStyle: "bold", // Font style
                    halign: "center", // Horizontal alignment (center)
                };

                // Customize body styles
                const bodyStyles = {
                    lineWidth: 0.1, // Border width for body
                    lineColor: [69, 69, 69], // Border color (RGB)
                };
                const footerStyles = {
                    fillColor: [69, 69, 69], // Background color (RGB)
                    textColor: [255, 255, 255], // Text color (RGB)
                };

                const columnStyles = {
                    index: {
                        halign: "center",
                        valign: "middle",
                        cellWidth: 10,
                    },
                    date: { halign: "center", valign: "middle" },
                    invoice_no: { halign: "center", valign: "middle" },
                    product_name: { halign: "center", valign: "middle" },
                    return_qty: {
                        halign: "center",
                        valign: "middle",

                    },
                    qty: { halign: "center" },
                    return_price: { halign: "center" },
                    client_name: { valign: "middle" },
                    price: { halign: "right" },
                    value: { halign: "right" },
                };
                doc.autoTable(exportColumns, formattedData, {
                    headStyles: headStyles, // Apply header styles
                    columnStyles: columnStyles,
                    bodyStyles: bodyStyles,
                    theme: "grid",

                    footStyles: footerStyles,
                    startY: 43, // Adjust this value to position the table below the header
                    didParseCell: function (data) {
                        // Apply colspan to the "date" and "sinNo" columns
                        if (data.section === "body") {
                            if (
                                data.column.dataKey === "invoice_no" &&
                                data.cell.raw !== ""
                            ) {
                                data.cell.rowSpan = data.row.raw.rowSpan; // Apply colspan of 3 to the date column
                            }
                            if (data.column.dataKey === "index") {
                                data.cell.rowSpan = data.row.raw.rowSpan; // Apply colspan of 3 to the sinNo column
                            }
                            if (data.column.dataKey === "client_name") {
                                data.cell.rowSpan = data.row.raw.rowSpan; // Apply colspan of 3 to the sinNo column
                            }


                        }
                    },
                    didDrawCell: function (data) {
                        let doc = data.doc;
                        let lastY = data.cell.y + data.cell.height + 6; // Adjust the position below the table
                        // Check if the current cell is the last cell of the last row
                        doc.setFontSize(13);
                        doc.setFont("Arial", "bold");
                        // Set font to bold for the totals

                        if (
                            data.row.index === data.table.body.length - 1 &&
                            data.column.index === data.table.columns.length - 1
                        ) {

                            // Add your custom content below the table
                            // Calculate the x positions for right-aligned text
                            const pageWidth = doc.internal.pageSize.getWidth();
                            const totalSalesString =
                                "Total value:  " + total.toString();

                            const totalPurchaseWidth =
                                doc.getTextDimensions(totalSalesString).w;

                            const salesX = pageWidth - totalPurchaseWidth - 14; // Adjust padding as needed

                            // Add the text
                            doc.text(totalSalesString, salesX, lastY);

                            // Add the text
                        }
                    },
                });

                doc.save(`Purchase Details Report.pdf`);
            });
        });
    };
    let total = salesReturn.reduce((acc, item) => {
        let itemTotal = item.details.reduce((innerAcc, list) => {
            return innerAcc + Number(list.total);
        }, 0);
        return acc + itemTotal;
    }, 0);

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Sales Return
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - SalesReturn
                    </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 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>
                        </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 SalseRetutnReport;
