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 { info } from "autoprefixer";
import { AutoComplete } from "primereact/autocomplete";

function PurchaseInvoice({ auth }) {
    const { permission } = useContext(authUser);
    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [purchase, setPurchase] = useState([]);
    const [shop, setShop] = useState([]);
    const conponentPDF = useRef();
    const toast = useRef(null);
    const [company, setCompany] = useState([]);
    const [companyId, setCompanyId] = useState(null);
    const [searchValue, setSearchValue] = useState({
        company: "",
    });

    useEffect(() => {
        axios.get(route("sales.report.shop")).then((res) => {
            setShop(res.data.shop);
        });
    }, []);

    const search = () => {
        let form = new FormData();
        form.append("start", startDate);
        form.append("end", endDate);
        form.append("company_id", companyId);
        axios.post("purchase-report-search-invoice", form).then((res) => {
            setPurchase(res.data);
        });
    };
    const exportPDF = () => {
        const cols = [
            { field: "index", header: "SI" },
            { field: "company", header: "Company" },
            { field: "product_name", header: "Product Name" },
            { field: "purchase_date", header: "Purchase Date" },
            { field: "qty", header: "Qty" },
            { field: "price", header: "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 = "Purchase Invoice ";
                const reportTotallength = doc.getTextWidth(reportTitle);
                doc.setFontSize(12);
                doc.setFont("Arial", "bold");
                doc.text(
                    "Purchase Invoice 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 = Object.keys(purchaseFiltered).flatMap(
                    (key, index) => {
                        return Object.keys(purchaseFiltered[key].more).flatMap(
                            (moreKey) => {
                                return purchaseFiltered[key].more[
                                    moreKey
                                ].info.map((detail) => {
                                    return {
                                        index: index + 1, // Add index for each detail entry
                                        company: purchaseFiltered[key].supplier
                                            ? purchaseFiltered[key].supplier
                                                  .name
                                            : "Own Purchase",
                                        purchase_date: `${new Date(
                                            detail.date
                                        ).toLocaleDateString("en-US")}`, // Use key as date
                                        product_name:
                                            detail?.attribute?.product?.name +
                                            (detail.attribute
                                                ? ` (${detail.attribute.sku})`
                                                : ""),

                                        qty: detail.qty,
                                        price: detail.purchase,
                                        value: detail.total,
                                        rowSpan:
                                            purchaseFiltered[key].more[moreKey]
                                                .info.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,
                    },
                    company: { halign: "left", valign: "middle" },
                    product_name: { halign: "left", valign: "middle" },
                    purchase_date: {
                        halign: "center",
                        valign: "middle",
                        cellWidth: 30,
                    },
                    qty: { halign: "center" },
                    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 === "company" &&
                                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 === "product_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:  " + result.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 Invoice Report.pdf`);
            });
        });
    };

    const purchaseFiltered = {};
    purchase.forEach((item) => {
       
        
        const supplierKey = item.supplier_id ? item.supplier_id : "own";

        // Append the date to each purchase detail
        const purchaseDetailsWithDate = item.purchase_detalis.map((detail) => ({
            ...detail,
            date: item.date,
        }));

        if (purchaseFiltered[supplierKey]) {
            // Concatenate new details with existing details
            const datas = purchaseFiltered[supplierKey].details.concat(
                purchaseDetailsWithDate
            );

            // Initialize 'more' with the existing 'more' object if it exists, otherwise create a new object
            const more = purchaseFiltered[supplierKey].more || {};

            // Iterate over concatenated details to group by attribute_id
            datas.forEach((data) => {
                if (more[data.attribute_id]) {
                    more[data.attribute_id].info =
                        more[data.attribute_id].info.concat(data);
                } else {
                    more[data.attribute_id] = {
                        info: [data],
                    };
                }
            });

            // Update the supplier's details and 'more' object
            purchaseFiltered[supplierKey].details = datas;
            purchaseFiltered[supplierKey].more = more;
        } else {
            // Create a new entry for the supplier with initial details and 'more' object
            const more = {};

            purchaseDetailsWithDate.forEach((data) => {
                if (more[data.attribute_id]) {
                    more[data.attribute_id].info =
                        more[data.attribute_id].info.concat(data);
                } else {
                    more[data.attribute_id] = {
                        info: [data],
                    };
                }
            });

            purchaseFiltered[supplierKey] = {
                supplier: item.supplier,
                details: purchaseDetailsWithDate,
                more: more,
            };
        }
    });


    const filterCompany = (event) => {
        setTimeout(() => {
            axios
                .post(route("company-search"), { data: event.query })
                .then((response) => {
                    setCompany(response.data.suppliers);
                });
        }, 250);
    };
    const companyTemplateIOptionList = (option) => {
        return (
            <div className="country-item">
                <div>
                    {option.name} ({option.number})
                </div>
            </div>
        );
    };


    const result = Object.keys(purchaseFiltered)
    .map((item) => {
        return Object.keys(purchaseFiltered[item].more).map((listKey) => {
            const total = purchaseFiltered[item].more[listKey].info.reduce((acc, infoItem) => {
                return acc + Number(infoItem.total); // Ensure conversion to Number
            }, 0);
            return total;
        });
    })
    .flat()
    .reduce((acc, curr) => acc + curr, 0); // Sum the flattened array



    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium ">
                        Purchase Invoice
                    </h2>{" "}
                    <p className="text-skin-sub-header font-semibold text-xs">
                        {" "}
                        Home - PurchaseInvoice
                    </p>
                </>
            }
            headerButton={<></>}
        >
            <Toast ref={toast} />
            {/* View Table*/}
            <div className="card p-5">
                <div className="relative overflow-x-auto  sm:rounded-lg">
                    <div className="pb-4  ">
                        <div className="w-100% space-x-4 flex">
                            <div className="p-fluid grid formgrid">
                                <div className="field col-12 md:col-4">
                                    <label htmlFor="type">Starting Date</label>
                                    <Calendar
                                        value={startDate}
                                        onChange={(e) => {
                                            setStartDate(e.value);
                                        }}
                                        className="h-[41px]  text-[14px]"
                                    ></Calendar>
                                </div>
                            </div>
                            <div className="p-fluid grid formgrid">
                                <div className="field col-12 md:col-4">
                                    <label htmlFor="type">End Date</label>
                                    <Calendar
                                        value={endDate}
                                        onChange={(e) => {
                                            setEndDate(e.value);
                                        }}
                                        className="h-[41px]  text-[14px]"
                                    ></Calendar>
                                </div>
                            </div>
                            <div className="p-fluid grid formgrid">
                                <div className="field col-12 md:col-4">
                                    <label htmlFor="type">Search Company</label>
                                    <AutoComplete
                                        value={searchValue.company}
                                        suggestions={company}
                                        completeMethod={filterCompany}
                                        aria-label="customer_id"
                                        itemTemplate={
                                            companyTemplateIOptionList
                                        }
                                        onChange={(e) => {
                                            if (e.value.name) {
                                                setCompanyId(e.value.id);
                                            } else {
                                                setCompanyId(null);
                                            }

                                            setSearchValue((old) => {
                                                return {
                                                    ...old,
                                                    company: e.value.name
                                                        ? e.value.name +
                                                          " (" +
                                                          e.value.number +
                                                          ")"
                                                        : e.value,
                                                };
                                            });
                                        }}
                                        className="w-full h-10"
                                    />
                                </div>
                            </div>
                            <div className="p-fluid grid formgrid">
                                <div className="field col-12 md:col-4 mt-6">
                                    <Button
                                        type="button"
                                        label="Search"
                                        onClick={search}
                                        className="p-button-success h-[41px]  text-[14px] "
                                    />
                                </div>
                            </div>

                            {purchase.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>
                    <div ref={conponentPDF}>

                    <ReportInfo
                                        heading={[
                                            "Company",
                                            "Product Name",
                                            "Purchase Date",
                                            "QTY",
                                            "Unit",
                                            "Purchase Price",
                                            "Total Price",
                                        ]}
                                    >
                        {Object.keys(purchaseFiltered).map((item, index) => {
                            return (
                                <>
                              
                                
                                        {Object.keys(
                                            purchaseFiltered[item].more
                                        ).map((lists) => {
                                            return (
                                                <>
                                                    <tbody>
                                                        {purchaseFiltered[
                                                            item
                                                        ].more[lists].info.map(
                                                            (list, index) => {
                                                                return (
                                                                    <tr className="bg-white border-b hover:bg-gray-50">
                                                                        {index ==
                                                                            0 && (
                                                                            <>
                                                                                <td
                                                                                    className="text-center border border-gray-300"
                                                                                    rowSpan={
                                                                                        purchaseFiltered[
                                                                                            item
                                                                                        ]
                                                                                            .more[
                                                                                            lists
                                                                                        ]
                                                                                            .info
                                                                                            .length
                                                                                    }
                                                                                >
                                                                                    {purchaseFiltered[
                                                                                        item
                                                                                    ]
                                                                                        .supplier
                                                                                        ? purchaseFiltered[
                                                                                              item
                                                                                          ]
                                                                                              .supplier
                                                                                              .name
                                                                                        : "Own Purchase"}{" "}
                                                                                </td>
                                                                                <td
                                                                                    className="text-center bg-white border border-gray-300"
                                                                                    rowSpan={
                                                                                        purchaseFiltered[
                                                                                            item
                                                                                        ]
                                                                                            .more[
                                                                                            lists
                                                                                        ]
                                                                                            .info
                                                                                            .length
                                                                                    }
                                                                                >
                                                                                    {
                                                                                        purchaseFiltered[
                                                                                            item
                                                                                        ]
                                                                                            .more[
                                                                                            lists
                                                                                        ]
                                                                                            .info[0]
                                                                                            .attribute
                                                                                            .product
                                                                                            .name
                                                                                    }{" "}
                                                                                    {purchaseFiltered[
                                                                                        item
                                                                                    ]
                                                                                        .more[
                                                                                        lists
                                                                                    ]
                                                                                        .info[0]
                                                                                        .attribute
                                                                                        ? `(${purchaseFiltered[item].more[lists].info[0].attribute.sku})`
                                                                                        : ""}
                                                                                </td>
                                                                            </>
                                                                        )}
                                                                        <th
                                                                            scope="row"
                                                                            className="px-6 py-4 font-medium text-center text-gray-900 whitespace-nowrap border border-gray-300"
                                                                        >
                                                                            {new Date(
                                                                                list.date
                                                                            ).toLocaleDateString(
                                                                                "en-us"
                                                                            )}
                                                                        </th>

                                                                        <td
                                                                            scope="col"
                                                                            className="px-6 py-4 text-bold text-black text-center border border-gray-300"
                                                                        >
                                                                            {
                                                                                list.qty
                                                                            }
                                                                        </td>

                                                                        <td
                                                                            scope="col"
                                                                            className="px-6 py-4 text-bold text-black text-center border border-gray-300"
                                                                        >
                                                                            {list
                                                                                .attribute
                                                                                .unit
                                                                                ? list
                                                                                      .attribute
                                                                                      .unit
                                                                                      .name
                                                                                : "N/A"}
                                                                        </td>
                                                                        <td
                                                                            scope="col"
                                                                            className="px-6 py-4 text-bold text-black text-right border border-gray-300"
                                                                        >
                                                                            {
                                                                                list.purchase
                                                                            }{" "}
                                                                            <span className="w-5">
                                                                                ৳
                                                                            </span>
                                                                        </td>

                                                                        <td
                                                                            scope="col"
                                                                            className="px-6 py-4  text-bold text-black text-right border border-gray-300"
                                                                        >
                                                                            {
                                                                                list.total
                                                                            }{" "}
                                                                            <span className="w-5">
                                                                                ৳
                                                                            </span>
                                                                        </td>
                                                                    </tr>
                                                                );
                                                            }
                                                        )}
                                                    </tbody>
                                                </>
                                            );
                                        })}

                                    
                                  
                                </>
                            );
                        })}
                            <tfoot className="bg-gray-100 ">
                                            <tr>
                                                <td
                                                    scope="col"
                                                    colspan={6}
                                                    className=" text-right text-black font-bold px-6 py-3"
                                                >
                                                    Total :
                                                </td>
                                                <td className="font-bold text-black pr-6  text-right">
                                                {result}{" "}
                                                    <span className="w-5">
                                                        ৳
                                                    </span>
                                                </td>
                                            </tr>
                                        </tfoot>
                        </ReportInfo>
                        
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

export default PurchaseInvoice;
