import React, { useContext } from "react";

import defaultLogo from "../../../../public/defualt/defualtLogo.jpg";
import { toWords } from "number-to-words";
import { SHOP_INFO, INVOICE_DEFAULTS } from "@/Utils/constants";
import { authUser } from "@/Components/AuthProvider";
import { isBusinessIdIn } from "@/Utils/helper";
function Print({ sales, auth }) {
    const { permission } = useContext(authUser);
    const invoiceData = {
        invoiceNumber: sales.invoice_no,
        date: new Date(sales.created_at).toLocaleDateString("en-GB", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            timeZone: "UTC", // or your actual server timezone
        }),

        company: {
            name: SHOP_INFO.name,
            address: SHOP_INFO.address,
            email: SHOP_INFO.email,
            provider: auth.shop_info.provider,
            manager: auth.shop_info.manager,
            phone: SHOP_INFO.phone,
            slogan: SHOP_INFO.slogan,
        },
        customer: {
            name: sales?.customer?.name,
            address: sales?.customer?.address,
            phone: sales?.customer?.number,
            email: sales?.customer?.email,
            code: sales?.customer?.code,
        },
        items:
            sales?.details?.map((item) => ({
                description: `${item?.product?.name ?? ""}${
                    item?.arribute?.gold_unit?.name
                        ? ` | Gold: ${item?.arribute?.gold_weight ?? 0} ${
                              item?.arribute?.gold_unit?.name
                          }`
                        : ""
                }${
                    item?.arribute?.diamond_unit?.name
                        ? ` | Diamond: ${item?.arribute?.diamond_weight ?? 0} ${
                              item?.arribute?.diamond_unit?.name
                          }`
                        : ""
                }`,

                sku: ` ${item?.arribute?.sku ? ` ${item.arribute.sku}` : ""}`,
                quantity: item.qty,
                warranty_code: item.warranty_code,
                after_discount_amount: item.after_discount,
                price: Number(item.price),
                total: Number(item.total),
                size: item?.arribute?.size?.name || "N/A",
                fqty: item.fqty ?? 0,
                allData: item,
            })) || [],
        totals: {
            subtotal: Number(sales.total),
            discount: Number(sales.discount),
            discount_2nd: Number(sales.discount_second),
            after_discount: Number(sales.after_discount),
            total: Number(sales.grand_total),
            previous_due: sales.previous_due || 0,
            payment: sales.current_payment || 0,
            order: sales.order_no || "N/A", // New field for order number
            transition_location: sales?.transition_location?.name || "N/A", // New field for transition location
        },
    };

    const { invoiceNumber, date, company, customer, items, totals } =
        invoiceData;

    const data = Array.from({ length: 50 }, (_, index) => ({
        description: `Item ${index + 1}`,
        quantity: Math.floor(Math.random() * 10) + 1,
        price: Math.random() * 100,
        total: Math.random() * 500,
    }));

    return (
        <div className="w-full h-[80vh]  break-after-avoid-page hidden print:bg-white print:relative print:block">
            {/* Content Area */}
            <div className=" px-6 print:px-12">
                <table className="w-full ">
                    <thead>
                        <tr>
                            <td colSpan={8} className=" pb-4">
                                <div className="border-b pb-4 flex justify-between items-center   ">
                                    <div className="text-left w-[14.7rem]">
                                        <h2 className="text-xl  pb-2 relative print:font-prose-antique ">
                                            {company.name}
                                            {company.slogan && (
                                                <p className=" text-right print:font-corsiva-regular text-[12px]  absolute right-[22px] top-[16px]">
                                                    {company.slogan}
                                                </p>
                                            )}
                                        </h2>

                                        <p className="text-sm">
                                            {company.address}
                                        </p>

                                        <p className="text-sm">
                                            Email: {company.email}
                                        </p>
                                    </div>
                                    <div className=" flex-1">
                                        <p className=" !-ml-[100px] text-center font-bold text-xl">
                                            INVOICE
                                        </p>
                                    </div>

                                    <div className=" ">
                                        <img
                                            src={SHOP_INFO.companyLogo || defaultLogo}
                                            alt=" Logo"
                                            className="w-20 h-20"
                                        />
                                    </div>
                                </div>

                                <div className="flex justify-between mt-3 text-gray-600">
                                    {/* Left: Billing info */}
                                    <div>
                                        <p className="font-bold mb-1 text-[13px]">
                                            {customer.code &&
                                                `Customer ID: (${customer.code})`}
                                        </p>
                                        <p className="text-sm">
                                            {customer.name
                                                ? `Name: ${customer.name}`
                                                : ""}
                                        </p>
                                        <p className="text-sm text-[13px]">
                                            {customer.phone
                                                ? `Phone: ${customer.phone}`
                                                : ""}{" "}
                                        </p>
                                        <p className="text-sm">
                                            {customer.email
                                                ? `Email: ${customer.email}`
                                                : ""}
                                        </p>
                                        <p className="text-sm">
                                            {customer.address
                                                ? `Address: ${customer.address}`
                                                : ""}
                                        </p>
                                    </div>

                                    {/* Right: Invoice info */}
                                    <div className="text-right">
                                        <p>
                                            <span className="font-bold text-[13px]">
                                                Invoice date:{" "}
                                            </span>
                                            <span className="text-[13px]">
                                                {date}
                                            </span>
                                        </p>
                                        <p>
                                            <span className="font-bold text-[13px]">
                                                Invoice number:{" "}
                                            </span>
                                            <span className="text-[13px]">
                                                {" "}
                                                {invoiceNumber}
                                            </span>
                                        </p>
                                        {permission.includes(
                                            "sales_order_view"
                                        ) && (
                                            <p>
                                                <span className="font-bold text-[13px]">
                                                    Order No:{" "}
                                                </span>
                                                <span className="text-[13px]">
                                                    {" "}
                                                    {totals.order}
                                                </span>
                                            </p>
                                        )}

                                        {permission.includes(
                                            "sales_person_pos_view"
                                        ) && (
                                            <p>
                                                <span className="font-bold text-[13px]">
                                                    SalesPerson:{" "}
                                                </span>
                                                {totals.transition_location}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </td>
                        </tr>
                        {isBusinessIdIn([6]) ? (
                            <tr>
                                <th className="border py-2 px-4 text-left text-[12px]">
                                    SKU
                                </th>
                                <th className="border py-2 px-4 text-left text-[12px] !w-[100px]">
                                    DESCRIPTION
                                </th>
                                <th className="border py-2 px-4 text-left text-[12px]">
                                    SIZE
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    QTY
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    FQ
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    PRICE Tk.
                                </th>
                                <th className="border py-2 ! w-[60px] px-4 text-center text-[12px]">
                                    Dsc Tk.
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    TOTAL Tk.
                                </th>
                            </tr>
                        ) : (
                            <tr>
                                <th
                                    colSpan={3}
                                    className="border py-2 px-4 text-left text-[12px] !w-[100px]"
                                >
                                    DESCRIPTION
                                </th>

                                <th className="border py-2 px-4 text-center text-[12px]">
                                    QTY
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    PRICE Tk.
                                </th>
                                <th className="border py-2 ! w-[60px] px-4 text-center text-[12px]">
                                    Dsc Tk.
                                </th>
                                <th className="border py-2 px-4 text-center text-[12px]">
                                    TOTAL Tk.
                                </th>
                            </tr>
                        )}
                    </thead>
                    <tbody>
                        {items.map((item, index) => {
                            return (
                                <>
                                    {/* Data row */}
                                    {isBusinessIdIn([6]) ? (
                                        <tr key={index}>
                                            <td className="border py-2 px-4 text-[12px] text-center">
                                                {item.sku}
                                            </td>
                                            <td className="border py-2 px-4 text-[10px]">
                                                {item.description}
                                                <br />
                                                {item?.warranty_code && (
                                                    <span className="text-sm text-gray-500">
                                                        {" "}
                                                        {item.warranty_code}
                                                    </span>
                                                )}
                                            </td>
                                            <td className="border py-2 text-[10px]  px-4">
                                                {item.size}
                                            </td>
                                            <td className="border py-2 px-4 text-[10px] text-center">
                                                {(() => {
                                                    const id =
                                                        parseInt(
                                                            item?.quantity
                                                        ) || 0; // Use your value for id
                                                    const converted_ratio =
                                                        parseInt(
                                                            item?.allData
                                                                ?.arribute?.unit
                                                                ?.converted_ratio
                                                        );

                                                    if (
                                                        !converted_ratio ||
                                                        converted_ratio === 0
                                                    ) {
                                                        // No box size info
                                                        return `${id} Pcs`;
                                                    }

                                                    if (
                                                        id === converted_ratio
                                                    ) {
                                                        // Exactly one box
                                                        return `1 Box`;
                                                    }

                                                    if (id < converted_ratio) {
                                                        // Less than a box, show only pieces
                                                        return `${id} Pcs`;
                                                    }

                                                    // More than a box
                                                    const boxes = Math.floor(
                                                        id / converted_ratio
                                                    );
                                                    const loose =
                                                        id % converted_ratio;

                                                    if (loose === 0) {
                                                        // Only full boxes
                                                        return `${boxes} Box`;
                                                    }

                                                    // Boxes plus extra pieces
                                                     `${boxes} Box | ${loose} Pcs`;
                                                     return item.quantity;
                                                })()}
                                            </td>
                                            <td className="border py-2 px-4 text-[10px] text-center">
                                                {item.fqty ?? 0} Pcs
                                            </td>
                                            <td className="border py-2 px-8 text-[10px] text-center">
                                                {item.price.toFixed(2)}
                                            </td>
                                            <td className="border py-2 px-7 text-[10px]  text-center">
                                                {item?.after_discount_amount ??
                                                    0}
                                            </td>
                                            <td className="border py-2 px-4 text-[10px] text-end">
                                                {item.total.toFixed(2)}
                                            </td>
                                        </tr>
                                    ) : (
                                        <tr key={index}>
                                            <td
                                                colSpan={3}
                                                className="border py-2 px-4  text-[10px]"
                                            >
                                                {item.description}{" "}
                                                <span className="text-[9px] text-gray-800">
                                                    {[
                                                        item?.allData?.arribute
                                                            ?.sku &&
                                                            `SKU: ${item.allData.arribute.sku}`,
                                                        item?.allData?.arribute
                                                            ?.brand?.name &&
                                                            `Brand: ${item.allData.arribute.brand.name}`,
                                                        item?.allData?.arribute
                                                            ?.color?.name &&
                                                            `Color: ${item.allData.arribute.color.name}`,
                                                        item?.allData?.arribute
                                                            ?.size?.name &&
                                                            `Size: ${item.allData.arribute.size.name}`,
                                                        item?.allData?.arribute
                                                            ?.model?.name &&
                                                            `Model: ${item.allData.arribute.model.name}`,
                                                        item?.allData?.arribute
                                                            ?.origin?.name &&
                                                            `Origin: ${item.allData.arribute.origin.name}`,
                                                    ]
                                                        .filter(Boolean)
                                                        .join(", ")}
                                                </span>
                                                <br />
                                                {item?.warranty_code && (
                                                    <span className="text-sm text-gray-500">
                                                        {" "}
                                                        {item.warranty_code}
                                                    </span>
                                                )}
                                            </td>

                                            <td className="border py-2 px-4 text-[10px] text-center">
                                                {(() => {
                                                    return item.quantity;
                                                })()}
                                            </td>
                                            <td className="border py-2 px-8 text-[10px] text-center">
                                                {item.price.toFixed(2)}
                                            </td>
                                            <td className="border py-2 px-7 text-[10px]  text-center">
                                                {item?.after_discount_amount ??
                                                    0}
                                            </td>
                                            <td className="border py-2 px-4 text-[10px] text-end">
                                                {item.total.toFixed(2)}
                                            </td>
                                        </tr>
                                    )}
                                </>
                            );
                        })}

                        <tr>
                            <td
                                colSpan={permission.includes("fqty_pos") ? 7 : 6}
                                className="border py-2 px-4  text-end text-[12px]"
                            >
                                Sub-Total
                            </td>
                            <td className="border py-2 text-[12px] px-4 text-end">
                                {totals.subtotal.toFixed(2)}
                            </td>
                        </tr>

                        <tr>
                            <td
                                colSpan={permission.includes("fqty_pos") ? 7 : 6}
                                className="border py-2 px-4   text-end text-[12px]"
                            >
                                Discount (Amount)
                            </td>
                            <td className="border py-2 px-4 text-[12px] text-end">
                                {(totals?.after_discount ?? 0).toFixed(2)}
                            </td>
                        </tr>
                        {/* <tr>
                            <td
                                colSpan={7}
                                className="border py-2 px-4  text-end text-[12px]"
                            >
                                Total
                            </td>
                            <td className="border py-2 px-4 text-end">
                                {totals.total.toFixed(2)}
                            </td>
                        </tr> */}

                        <tr>
                            <td
                                colSpan={permission.includes("fqty_pos") ? 7 : 6}
                                className="border py-2 px-4  text-end text-[12px]"
                            >
                                Grand Total
                            </td>
                            <td className="border py-2 px-4 text-[12px]  text-end">
                                {Number(totals.total).toFixed(
                                    2
                                )}
                            </td>
                        </tr>

                        {permission.includes("sales_invoice_due_view") && (
                            <>
                                <tr>
                                    <td
                                        colSpan={permission.includes("fqty_pos") ? 7 : 6}
                                        className="border py-2 px-4  text-end text-[12px]"
                                    >
                                        Current Pay
                                    </td>
                                    <td className="border py-2 px-4 text-[12px] text-end">
                                        {Number(totals?.payment ?? 0).toFixed(
                                            2
                                        )}
                                    </td>
                                </tr>
                                <tr>
                                    <td
                                        colSpan={permission.includes("fqty_pos") ? 7 : 6}
                                        className="border py-2 px-4  text-end text-[12px]"
                                    >
                                    This invoice Due
                                    </td>
                                    <td className="border py-2 px-4 text-[12px]  text-end">
                                        {Number(
                                            totals.total - totals.payment
                                        ).toFixed(2)}
                                    </td>
                                </tr>
                            </>
                        )}
                        <tr className="border-none border-0">
                            <td
                                colSpan={4}
                                className="border-none border-0 !border-b-0 p-2"
                            >
                                <div className="">
                                    <span className="text-[12px]">
                                        In Word:{" "}
                                    </span>
                                    <span className="text-[12px]">
                                        {totals.total
                                            ? toWords(
                                                  totals.total.toFixed(2)
                                              )[0].toUpperCase() +
                                              toWords(
                                                  totals.total.toFixed(2)
                                              ).slice(1)
                                            : ""}
                                    </span>

                                    <br />

                                    {permission.includes(
                                        "sales_invoice_due_view"
                                    ) && (
                                        <>
                                            <span className="text-[12px]">
                                                {" "}
                                                Total Due :{" "}
                                            </span>
                                            <span className="text-[12px]">
                                                {totals.previous_due.toFixed(2)}
                                            </span>
                                        </>
                                    )}
                                </div>
                            </td>
                        </tr>
                    </tbody>

                    <tfoot>
                        <tr className="">
                            <td colSpan={5} className="py-14">
                                <div className="text-sm mt-6 print:pb-3 max-w-4xl mx-auto ">
                                    {/* Signature Section */}
                                    {/* <div className="flex justify-between">
                              
                                        <div className="w-1/2 pr-6 flex items-center">
                                            <span className="mr-3 whitespace-nowrap ">
                                                Authorized Signature:
                                            </span>
                                            <div className="border-b-2 min-w-[160px] border-gray-700 flex-grow" />
                                        </div>

                                     
                                        <div className="w-1/2 pl-6 flex items-center justify-end">
                                            <span className="mr-3 whitespace-nowrap ">
                                                Customer Signature:
                                            </span>
                                            <div className="border-b-2 min-w-[160px] border-gray-700 flex-grow" />
                                        </div>
                                    </div> */}
                                </div>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <div className="print:relative">
                {/* Footer (Signatures) */}
                <div className="mt-12 text-sm max-w-4xl mx-auto print:fixed print:bottom-10 print:left-5 print:right-5">
                    <div className="flex justify-between gap-10">
                        {/* Customer Signature */}
                        <div className="w-1/2 flex flex-col items-end">
                            <div className="flex items-center w-full justify-end">
                                <span className="mr-2 whitespace-nowrap">
                                    Customer Signature:
                                </span>
                                <div className="border-b-2 border-gray-700 flex-grow min-w-[160px]" />
                            </div>
                        </div>

                        {/* Authorized Signature */}
                        <div className="w-1/2 flex flex-col items-start">
                            <div className="flex items-center w-full">
                                <span className="mr-2 whitespace-nowrap">
                                    Authorized Signature:
                                </span>
                                <div className="border-b-2 border-gray-700 flex-grow min-w-[160px]" />
                            </div>
                        </div>
                    </div>

                    {/* Return Policy Note */}
                    {INVOICE_DEFAULTS.footerNote && (
                        <p className="text-center text-[11px] mt-10 text-gray-600 leading-relaxed">
                            <span className="font-bold">NB:</span>{" "}
                            <span>{INVOICE_DEFAULTS.footerNote}</span>
                        </p>
                    )}
                </div>
            </div>
        </div>
    );
}

export default Print;
