import { React, useState, useContext } 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 { authUser } from "@/Components/AuthProvider";
import { Calendar } from "primereact/calendar";
import ReportInfo from "@/Components/ReportInfo";

function DailyKhataReport({ auth }) {
    const { permission } = useContext(authUser);
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();

    const conponentPDF = useRef();
    const toast = useRef(null);
    const [stock, setStock] = useState([]);

    const cols = [
        { field: "index", header: "SINo" },
        { field: "productName", header: "Product Name" },
        { field: "TotalStock", header: "Total Stock" },
        { field: "TotalSales", header: "Total Sales" },
        { field: "StockAfterSalse", header: "Stock After Salse" },
        { field: "StockValue", header: "Stock Value" },
    ];

    const exportColumns = cols.map((col) => ({
        title: col.header,
        dataKey: col.field,
    }));

    const search = () => {
        let form = new FormData();
        form.append("start", startDate);
        form.append("end", endDate);
        axios.post("stock-report-filter", form).then((res) => {
            setStock(res.data);
        });
    };
    const openInNewTab = async () => {
            const data =  search();
            const pdfDoc = await window.generatePDFView(
                data,
                window.reportModes.stockReport,
                false
            );
            renderPDF(pdfDoc, "CompanyDue.pdf");
        };
    const exportPDF = () => {
        import("jspdf").then((jsPDF) => {
            import("jspdf-autotable").then(() => {
                const doc = new jsPDF.default("p", "mm", "a4");
                const pageWidth = doc.internal.pageSize.getWidth();

                // Add a title or header above the table
                doc.setFontSize(15);
                doc.setFont("Arial", "bold");
                doc.text("Unity", 70, 20); // Position the header at (x, y)

                doc.setFontSize(12);
                doc.setFont("Arial", "bold");
                doc.text("Stock Report.", 95, 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);

                // Format the data to include the formatted date
                const formattedData = stock.map((item, index) => ({
                    ...item,
                    index: index + 1, 
                    productName: item.name,
                    TotalStock: item.total_purchase_qty,
                    TotalSales: item.total_sales_qty,
                    StockAfterSalse: item.current_qty,
                    StockValue: item.total_stock,
                }));

                // 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 = {
                    productName: { halign: "left" },
                    TotalStock: { halign: "center" },
                    TotalSales: { halign: "center" },
                    StockAfterSalse: { halign: "center" },
                    StockValue: { halign: "right" },
                };
                doc.autoTable(exportColumns, formattedData, {
                    headStyles: headStyles, // Apply header styles
                    columnStyles: columnStyles,
                    bodyStyles: bodyStyles,
                    theme: "grid",
                    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 totalValue =
                                "Total value:  " + stockValue.toString();

                            const stockValueWidth =
                                doc.getTextDimensions(stockValue).w;

                            const salesX = pageWidth - stockValueWidth -40; // Adjust padding as needed

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

                            // Add the text
                        }
                    },
                    footStyles: footerStyles,
                    startY: 40, // Adjust this value to position the table below the header
                });
               
                const blobUrl = doc.output("bloburl"); // Create a Blob URL for preview
                
                // Option 1: Open in a new tab
                window.open(blobUrl);
                
                // Option 2: Set as source of an iframe for inline preview
                document.getElementById("pdfPreview").src = blobUrl;
            });
        });
    };

    let stockValue = stock.reduce((old, acc) => {
        return (old += Number(acc.total_stock));
    }, 0);

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Stock Report
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - Stock 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 className="block text-sm font-medium text-gray-600 mb-2">Starting Date</label>
                                    <Calendar
                                        value={startDate}
                                        onChange={(e) => {
                                            setStartDate(e.value);
                                        }}
                                        
                                        required
                                        className="h-[41px]  text-[14px]"
                                    ></Calendar>
                                
                            </div>
                           
                                  <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);
                                        }}
                                        required
                                        className="h-[41px]  text-[14px]"
                                    ></Calendar>
                                </div>
                            
                            </div>

                             <div className="mt-10 flex justify-center">
                                                       <Button
                                                           type="button"
                                                           label="🔍 View Report"
                                                           onClick={openInNewTab}
                                                           className="px-6 py-3 rounded-xl bg-blue-600 text-white font-semibold shadow hover:bg-blue-700 transition duration-200 text-sm"
                                                       />
                                                   </div>
                            {/* {stock.length != 0 && (
                                <div className="p-fluid grid formgrid">
                                    <div className="field col-12 md:col-4 mt-6">
                                        <Button
                                            type="button"
                                            label="Download"
                                            onClick={exportPDF}
                                            className="p-button-indo h-[41px]  text-[14px] "
                                        />
                                    </div>
                                </div>
                            )} */}
                        
                    </div>
                    <div ref={conponentPDF} className=" flex  flex-col gap-5">
                        {stock.length != 0 && (
                            <div>
                                <ReportInfo
                                    heading={[
                                        "Product Name",
                                        "Total Stock",
                                        "Total Sales",
                                        "Stock After Sale",
                                        "Stock Value",
                                    ]}
                                >
                                    <tbody>
                                        {stock.map((item, index) => (
                                            <>
                                                <tr className="bg-white border-b hover:bg-gray-50">
                                                    <td
                                                        scope="col"
                                                        className="px-6 py-4  text-bold text-black text-left border border-gray-300"
                                                    >
                                                        {item.name}
                                                    </td>

                                                    <td
                                                        scope="col"
                                                        className="px-6 py-4  text-bold text-black text-center border border-gray-300"
                                                    >
                                                        {
                                                            item.total_purchase_qty
                                                        }{" "}
                                                    </td>
                                                    <td
                                                        scope="col"
                                                        className="px-6 py-4  text-bold text-black text-center border border-gray-300"
                                                    >
                                                        {item.total_sales_qty}{" "}
                                                    </td>
                                                    <td
                                                        scope="col"
                                                        className="px-6 py-4  text-bold text-black text-center border border-gray-300"
                                                    >
                                                        {item.current_qty}{" "}
                                                    </td>
                                                    <td
                                                        scope="col"
                                                        className="px-6 py-4  text-bold text-black text-right border border-gray-300"
                                                    >
                                                        {item.total_stock.toFixed(
                                                            2
                                                        )}{" "}
                                                    </td>
                                                </tr>
                                            </>
                                        ))}
                                    </tbody>
                                    <tfoot className="bg-gray-100 ">
                                        <tr>
                                            <td
                                                scope="col"
                                                colspan={4}
                                                className=" text-right text-black font-bold px-6 py-3"
                                            >
                                                Total :
                                            </td>

                                            <td className="font-bold text-black pr-6  text-right">
                                                {stockValue.toFixed(2)}{" "}
                                                <span className="w-5">৳</span>
                                            </td>
                                        </tr>
                                    </tfoot>
                                </ReportInfo>
                            </div>
                        )}
                    </div>
                </div>
              
            </div>
        </AuthenticatedLayout>
    );
}

export default DailyKhataReport;
