import React from "react";
import { toWords } from "number-to-words";
import "../../../css/receipt.css";
import logo from "../../../../public/defualt/defualtLogo.jpg";
import { SHOP_INFO } from "@/Utils/constants";

const QuotationPrintPage = ({ quotationInfo }) => {
  if (!quotationInfo || !quotationInfo.product_quotation_details) {
    return null;
  }

  // Calculate totals
  let totalBaseAmount = quotationInfo.product_quotation_details.reduce(
    (acc, item) => {
      const unitPrice = Number(item.unit_price || 0);
      const quantity = Number(item.quantity || 0);
      const baseAmount = Number(item.total || 0) || (unitPrice * quantity);
      return acc + baseAmount;
    },
    0
  );

  let totalVAT = quotationInfo.product_quotation_details.reduce(
    (acc, item) => {
      return acc + Number(item?.vat || 0);
    },
    0
  );

  let totalTax = quotationInfo.product_quotation_details.reduce(
    (acc, item) => {
      return acc + Number(item?.tax || 0);
    },
    0
  );

  let grandTotal = totalBaseAmount + totalVAT + totalTax;

  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    const day = date.getDate();
    const suffix =
      day === 1 || day === 21 || day === 31
        ? "st"
        : day === 2 || day === 22
          ? "nd"
          : day === 3 || day === 23
            ? "rd"
            : "th";
    return `${day}${suffix} ${date.toLocaleDateString("en-GB", {
      month: "long",
      year: "numeric",
    })}`;
  };

  // Replace template tags with actual data
  const replaceTemplateTags = (htmlContent) => {
    if (!htmlContent) return "";

    const client = quotationInfo.client || {};
    // Get first active branch from client's branches, or first branch if no active branch
    const branches = client.branches || [];
    const activeBranch = branches.find(b => b.status === '1') || branches[0] || {};

    // Template mapping
    const replacements = {
      "{date}": formatDate(quotationInfo.date) || "",
      "{quotation_number}": quotationInfo.quotation_number || "",
      "{customer_name}": client.name || "",
      "{customer_code}": client.code || "",
      "{customer_number}": client.number || "",
      "{customer_email}": client.email || "",
      "{customer_address}": client.address || "",
      "{customer_phone}": client.number || "",
      "{branch_name}": activeBranch.branch_name || "",
      "{branch_code}": activeBranch.branch_code || "",
      "{contact_person}": activeBranch.contact_person || "",
      "{branch_address}": activeBranch.address || "",
      "{branch_phone}": activeBranch.phone || "",
      "{branch_email}": activeBranch.email || "",
      "{payment_term}": quotationInfo.payment_term || "",
      "{tax_exclude_include}": quotationInfo.tax_exclude_include || "",
    };

    let replacedContent = htmlContent;

    // Replace all template tags
    Object.keys(replacements).forEach((tag) => {
      const regex = new RegExp(tag.replace(/[{}]/g, "\\$&"), "g");
      replacedContent = replacedContent.replace(regex, replacements[tag]);
    });

    return replacedContent;
  };

  return (
    <div className="w-full break-after-avoid-page print-view">
      {/* Content Area */}
      <div className="px-6 print:px-12">
        <table style={{ tableLayout: 'fixed', fontSize: '11px', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <td colSpan={12} className="pb-4">
                {/* Header Section with Logo and Shop Info */}
                <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">
                      {SHOP_INFO.name}
                      {SHOP_INFO.slogan && (
                        <p className="text-right print:font-corsiva-regular text-[12px] absolute right-[22px] top-[16px]">
                          {SHOP_INFO.slogan}
                        </p>
                      )}
                    </h2>
                    <p className="text-sm">
                      {SHOP_INFO.address}
                    </p>
                    <p className="text-sm">
                      Email: {SHOP_INFO.email}
                    </p>
                  </div>
                  <div className="flex-1">
                    <p className="!-ml-[100px] text-center font-bold text-xl">
                      QUOTATION
                    </p>
                  </div>
                  <div>
                    <img
                      src={logo}
                      alt="Logo"
                      className="w-20 h-20"
                    />
                  </div>
                </div>
              </td>
            </tr>

            {/* Custom Header from Quotation Text Editor */}
            {quotationInfo.product_quotation_setting?.header && (
              <tr>
                <td colSpan={12} className="py-3">
                  <div
                    className="text-[12px]"
                    dangerouslySetInnerHTML={{
                      __html: replaceTemplateTags(
                        quotationInfo.product_quotation_setting.header
                      ),
                    }}
                  />
                </td>
              </tr>
            )}

            {/* Table Header */}
            <tr>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '3%' }}>
                SL
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '18%' }}>
                DESCRIPTION
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '5%' }}>
                CAS#
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '5%' }}>
                CAT#
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '4%' }}>
                UNIT
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '5%' }}>
                QTY
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '8%' }}>
                UNIT PRICE
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '9%' }}>
                TOTAL AMOUNT
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '7%' }}>
                VAT @10%
              </th>

              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '12%' }}>
                TOTAL with VAT&TAX
              </th>
              <th className="border py-1 px-1 text-center text-[10px] font-semibold" style={{ width: '12%' }}>
                BRAND/ORIGIN
              </th>
            </tr>
          </thead>
          <tbody>
            {quotationInfo.product_quotation_details.map(
              (item, index) => {
                const unitPrice = Number(item.unit_price || 0);
                const quantity = Number(item.quantity || 0);
                // Use stored total as base amount, or calculate if not available
                const totalAmount = Number(item.total || 0) || (unitPrice * quantity);
                const vat = Number(item.vat || 0);
                const tax = Number(item.tax || 0);
                const totalWithVATAndTax =
                  totalAmount + vat + tax;

                return (
                  <tr key={index}>
                    <td className="border py-1 px-1 text-[10px] text-center">
                      {String(index + 1).padStart(2, "0")}
                    </td>
                    <td className="border py-1 px-1 text-[10px]">
                      {item.product_name ||
                        item.product?.name ||
                        "N/A"}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-center">
                      {item.attribute?.cas || "-"}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-center">
                      {item.attribute?.cat || "-"}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-center">
                      {item.attribute?.unit?.name || "Ps"}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-center">
                      {quantity.toFixed(2)}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-right">
                      {unitPrice.toLocaleString(
                        "en-US",
                        {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        }
                      )}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-right">
                      {totalAmount.toLocaleString(
                        "en-US",
                        {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        }
                      )}
                    </td>
                    <td className="border py-1 px-1 text-[10px] text-right">
                      {vat.toLocaleString("en-US", {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                      })}
                    </td>

                    <td className="border py-1 px-1 text-[10px] text-right">
                      {totalWithVATAndTax.toLocaleString(
                        "en-US",
                        {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        }
                      )}
                    </td>
                    <td className="border py-1 px-1 text-[10px]">
                      {[
                        item.attribute?.brand?.name,
                        item.attribute?.origin?.name,
                      ]
                        .filter(Boolean)
                        .join(", ") || "-"}
                    </td>
                  </tr>
                );
              }
            )}
          </tbody>
          <tfoot>
            <tr>
              <td
                colSpan={7}
                className="border py-1 px-1 text-right text-[10px] font-bold"
              >
                Grand Total:
              </td>
              <td className="border py-1 px-1 text-right text-[10px] font-bold">
                {totalBaseAmount.toLocaleString("en-US", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </td>

              <td className="border py-1 px-1 text-right text-[10px] font-bold">
                {totalTax.toLocaleString("en-US", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </td>
              <td className="border py-1 px-1 text-right text-[10px] font-bold">
                {grandTotal.toLocaleString("en-US", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </td>
              <td className="border py-1 px-1 text-[10px]"></td>
            </tr>
            <tr>
              <td
                colSpan={12}
                className="border py-1 px-1 text-left text-[10px]"
              >
                <span className="font-bold">In words: </span>
                <span className="font-normal">
                  {grandTotal
                    ? toWords(
                      grandTotal.toFixed(2)
                    )[0].toUpperCase() +
                    toWords(
                      grandTotal.toFixed(2)
                    ).slice(1)
                    : ""}
                </span>
              </td>
            </tr>
          </tfoot>
        </table>

        {/* Custom Footer from Quotation Text Editor */}
        {quotationInfo.product_quotation_setting?.footer && (
          <div
            className="mt-4 text-[12px]"
            dangerouslySetInnerHTML={{
              __html: replaceTemplateTags(
                quotationInfo.product_quotation_setting.footer
              ),
            }}
          />
        )}

        <div className="mt-8 text-[12px]">
          <p className="text-center mt-4">
            This is a computer generated document. No signature is
            required.
          </p>
        </div>
      </div>
    </div>
  );
};

export default QuotationPrintPage;
