import { useSiteContext } from "@/app/Context/SiteContext";
import { useFormattedPrice } from "@/app/utils/formatPrice";
import {
  formatDateWithTime,
  formatTime,
} from "@/app/utils/formattedDateWithTime";
import { getNameByCode } from "@/app/utils/getNameByCode";
import { useSupplierById } from "@/app/utils/getSupplierById";
import { getTaxById } from "@/app/utils/getTaxById";
import { numberToWords } from "@/app/utils/numberToWords";
import { parseArrayField } from "@/app/utils/parseArrayField";
import { apiUrl, frontEndUrl } from "@/app/utils/variables";

export default function PurchasePDF({
  brandSettings,
  form,
  settings,
  currency,
}) {
  const {
    totalAmountPayabale,
    selectedSupplier,
    currentSession,
    getCurrentCurrency,
    getCustomerDetails,
    lineItems,
    timeZone,
    finalPdfData,
    newTax,
  } = useSiteContext();
  const { formatPrice } = useFormattedPrice();

  const currentCurrency = getCurrentCurrency(form, currency) || form?.currency;





  const { data: supplier, isLoading, error } = useSupplierById(form?.supplier_id)





  const items =
    Array.isArray(lineItems) && lineItems.length > 0
      ? lineItems
      : (form?.line_items ?? []);





  let supplierInfo = form?.supplier_info;

  const safeDate = (dateStr) => {
    const d = new Date(dateStr);
    return isNaN(d.getTime()) ? new Date() : d;
  };


  const invoiceNumber = form?.itemNumber || form?.purchase_number || "";
  const customerName = supplierInfo?.[0]?.full_name || "";


  const taxRate = form?.add_tax
    ? Number(getTaxById(newTax, brandSettings?.global_tax)?.value)
    : 0;


  // Calculations

  // Calculations
  // ---- CALCULATE TOTALS DIRECTLY (SAFE) ----
  const totalBeforeTax = items.reduce((sum, item) => {
    const qty = Number(item.qty || 0);
    const price = Number(item.price || 0);
    const total = qty * price;

    const discount = item.discountPercentage
      ? (total * Number(item.discountPercentage)) / 100
      : Number(item.discountAmount || 0);

    return sum + (total - discount);
  }, 0);

  const totalVat = items.reduce((sum, item) => {
    const qty = Number(item.qty || 0);
    const price = Number(item.price || 0);
    const total = qty * price;

    const discount = item.discountPercentage
      ? (total * Number(item.discountPercentage)) / 100
      : Number(item.discountAmount || 0);

    const taxable = total - discount;
    return sum + (taxable * taxRate) / 100;
  }, 0);

  const netTotal = totalBeforeTax + totalVat;

  return (
    <div
      id="pdf-content"
      style={{
        fontFamily: "Arial, sans-serif",
        fontSize: "12px",
        margin: 0,
        padding: "20px",
        backgroundColor: "#fff",
        lineHeight: "1.4",
        maxWidth: "100%",
        margin: "0 auto",
      }}
    >
      {/* Header Section */}
      <table style={{ width: "100%", marginBottom: "20px" }}>
        <tbody>
          <tr>
            <td style={{ width: "50%", verticalAlign: "top" }}>
              {/* Company Logo and Info */}
              {brandSettings?.company_logo_color && (
                // <div
                //   className="h-[70px] w-[140px] bg-no-repeat bg-contain mb-5"
                //   style={{
                //     backgroundImage: `url(${`${apiUrl}/proxy?fileUrl=${frontEndUrl}${brandSettings?.company_logo_color}`})`,
                //     backgroundPosition: "left center",
                //   }}
                // ></div>

                <img
                  src={`${apiUrl}/proxy?fileUrl=${frontEndUrl}${brandSettings?.company_logo_color}`}
                  alt="Company Logo"
                  style={{
                    width: "120px",
                    height: "120px",
                    objectFit: "contain",
                    display: "block",
                    marginBottom: "12px",
                  }}
                />
              )}

              <div style={{ fontSize: "11px", color: "#333" }}>
                <div>
                  <strong>{brandSettings?.company_name}</strong>
                </div>
                <div>{brandSettings?.address_line_1}</div>
                <div>
                  {brandSettings?.city},{" "}
                  {getNameByCode(brandSettings?.state_province, "state")},{" "}
                  {getNameByCode(brandSettings?.country, "country")}{" "}
                  {brandSettings?.postal_zip_code}
                </div>
                <div>Phone: {brandSettings?.phone}</div>
                <div>Website: {brandSettings?.website}</div>
                <div>
                  TRN: {brandSettings?.tax_vat_registration_number || "N/A"}
                </div>
              </div>
            </td>
            <td
              style={{ width: "50%", textAlign: "right", verticalAlign: "top" }}
            >
              <h1
                style={{
                  fontSize: "21px",
                  fontWeight: 700,
                  color: `${brandSettings?.primary_color || "#000"}`,
                  marginBottom: "30px",
                }}
              >
                PURCHASE INVOICE
              </h1>
              <table style={{ marginLeft: "auto", fontSize: "11px" }}>
                <tbody>
                  <tr>
                    <td
                      style={{
                        padding: "2px 8px",
                        textAlign: "right",
                        fontWeight: "bold",
                      }}
                    >
                      DATE
                    </td>
                    <td
                      style={{ padding: "2px 8px", border: "1px solid #000" }}
                    >
                      {formatDateWithTime(form?.purchase_date, brandSettings)}
                      {/* -{" "}
                      {formatTime(timeZone)} */}
                    </td>
                  </tr>
                  <tr>
                    <td
                      style={{
                        padding: "2px 8px",
                        textAlign: "right",
                        fontWeight: "bold",
                      }}
                    >
                      INVOICE #
                    </td>
                    <td
                      style={{ padding: "2px 8px", border: "1px solid #000" }}
                    >
                      {invoiceNumber}
                    </td>
                  </tr>
                  <tr>
                    <td
                      style={{
                        padding: "2px 8px",
                        textAlign: "right",
                        fontWeight: "bold",
                      }}
                    >
                      SUPPLIER ID
                    </td>
                    <td
                      style={{ padding: "2px 8px", border: "1px solid #000" }}
                    >
                      {selectedSupplier?.supplier_id || form?.supplier_id || "-"}
                    </td>
                  </tr>
                </tbody>
              </table>
            </td>
          </tr>
        </tbody>
      </table>

      {/* Bill To and Ship To Section */}
      <div style={{ display: "flex", gap: "20px", paddingBottom: "10px" }}>
        {/* BILL TO table */}
        <table
          style={{
            width: "50%",
            border: "1px solid #000",
            borderCollapse: "collapse",
          }}
        >
          <thead>
            <tr>
              <th
                style={{
                  background: brandSettings?.primary_color,
                  color: "#fff",
                  fontWeight: 700,
                  padding: "5px",
                  fontSize: "13px",
                  border: "1px solid #000",
                  textAlign: "left",
                }}
              >
                BILL TO
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td
                style={{
                  padding: "10px",
                  border: "1px solid #000",
                  verticalAlign: "top",
                }}
              >
                <div
                  style={{
                    textTransform: "capitalize",
                  }}
                >
                  <strong>{customerName}</strong>
                </div>

                <div
                  style={{
                    textTransform: "capitalize",
                  }}
                >


                  <strong>{form?.supplier_info?.name || supplier?.name}</strong>
                </div>

                <div>Address: {form?.supplier_info?.address_line || supplier?.address_line}</div>
                <div>Tel: {form?.supplier_info?.contact_number || supplier?.contact_number}</div>
                <div>Email: {form?.supplier_info?.email || supplier?.email}</div>

                <div>TAX: {form?.supplier_info?.tax_number || supplier?.tax_number}</div>
                <div>Website: {form?.supplier_info?.website || supplier?.website}</div>
              </td>
            </tr>
          </tbody>
        </table>

        {/* SHIP TO table */}
        <table
          style={{
            width: "50%",
            border: "1px solid #000",
            borderCollapse: "collapse",
          }}
        >
          <thead>
            <tr>
              <th
                style={{
                  background: brandSettings?.primary_color,
                  color: "#fff",
                  fontWeight: 700,
                  padding: "5px",
                  fontSize: "13px",
                  border: "1px solid #000",
                  textAlign: "left",
                }}
              >
                SHIP TO
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td
                style={{
                  padding: "10px",
                  border: "1px solid #000",
                  verticalAlign: "top",
                }}
              >
                <div
                  style={{
                    textTransform: "capitalize",
                  }}
                >
                  <strong>{customerName}</strong>
                </div>
                <div
                  style={{
                    textTransform: "capitalize",
                  }}
                >


                  <strong>{form?.supplier_info?.name || supplier?.name}</strong>
                </div>

                <div>Address: {form?.supplier_info?.address_line || supplier?.address_line}</div>
                <div>Tel: {form?.supplier_info?.contact_number || supplier?.contact_number}</div>
                <div>Email: {form?.supplier_info?.email || supplier?.email}</div>

                <div>TAX: {form?.supplier_info?.tax_number || supplier?.tax_number}</div>
                <div>Website: {form?.supplier_info?.website || supplier?.website}</div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Items Table */}

      <table
        cellPadding="0"
        cellSpacing="0"
        style={{
          borderCollapse: "collapse",
          width: "100%",

          // border: `1px solid ${brandSettings?.primary_color || "#000"}`,
        }}
      >
        <thead>
          {[
            "ITEM DESCRIPTION",
            "QTY",
            "UNIT PRICE",
            "DISC",
            "TOTAL",
            "TAX",
            "LINE TOTAL",
          ].map((header, i) => (
            <th
              key={i}
              style={{
                background: `${brandSettings?.primary_color || "#000"}`,
                color: "#fff",
                padding: "7px 5px 3px 5px",
                fontWeight: 700,
                fontSize: "12px",
                whiteSpace: "nowrap",
                textAlign: "center",
                borderRight: i < 7 ? "1px solid #ffffff" : "none",
              }}
            >
              {header}
            </th>
          ))}
        </thead>

        <tbody>
          {items?.map((item, idx) => {
            const qty = Number(item.qty || 0);
            const price = Number(item.price || 0);
            const total = qty * price;
            const discount = item.discountPercentage
              ? (total * Number(item.discountPercentage)) / 100
              : Number(item.discountAmount || 0);
            const discountedTotal = total - discount;
            const taxAmount = (discountedTotal * taxRate) / 100;
            const finalAmount = discountedTotal + taxAmount;

            return (
              <tr key={idx}>
                <td
                  style={{
                    ...cellStyle,
                    width: "45%",
                  }}
                >
                  {item.item_name}
                </td>
                <td
                  style={{
                    ...cellStyle,
                    textAlign: "center",
                    width: "50px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {qty}
                </td>
                <td
                  style={{
                    ...cellStyle,
                    textAlign: "right",
                    width: "100px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {formatPrice(price, currentCurrency, false)}
                </td>
                <td
                  style={{
                    ...cellStyle,
                    textAlign: "right",
                    width: "100px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {formatPrice(discount, currentCurrency, false)}
                </td>
                <td
                  style={{
                    ...cellStyle,
                    textAlign: "right",
                    width: "100px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {formatPrice(discountedTotal, currentCurrency, false)}
                </td>

                <td
                  style={{
                    ...cellStyle,
                    textAlign: "right",
                    width: "100px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {formatPrice(taxAmount, currentCurrency, false)}
                </td>
                <td
                  style={{
                    ...cellStyle,
                    textAlign: "right",
                    fontWeight: "bold",
                    width: "100px",
                    whiteSpace: "nowrap",
                  }}
                >
                  {formatPrice(finalAmount, currentCurrency, false)}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <table>
        <tbody>
          {/* Totals Section */}
          <tr>
            <td
              rowSpan="5"
              style={{ verticalAlign: "top", width: "427px", width: "100%" }}
            >
              <div
                style={{
                  padding: "7px",
                  minHeight: "30px",
                  borderLeft: "solid thin black",
                  borderBottom: "solid thin black",
                  borderRight: 0,
                  //  width: "67%",
                }}
              >
                Amount in Words:{" "}
                <span className="uppercase font-bold">
                  {numberToWords(Number(netTotal))}
                </span>
              </div>
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                fontSize: "12px",
                backgroundColor: brandSettings?.primary_color || "#000",
                color: "#fff",
                whiteSpace: "nowrap",
              }}
            >
              SUB TOTAL:
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                fontSize: "12px",
                backgroundColor: brandSettings?.primary_color || "#000",
                color: "#fff",
                whiteSpace: "nowrap",
              }}
            >
              {formatPrice(totalBeforeTax, currentCurrency, false)}
            </td>
          </tr>
          <tr>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              TOTAL VAT:
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              {formatPrice(totalVat, currentCurrency, false)}
            </td>
          </tr>
          <tr>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              TOTAL WITH VAT:
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              {formatPrice(netTotal, currentCurrency, false)}
            </td>
          </tr>
          {/* <tr>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              TOTAL AMOUNT PAYABLE:
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              {formatPrice(totalAmountPayabale, currentCurrency, false)}
            </td>
          </tr>
          <tr>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              BALANCE AMOUNT:
            </td>
            <td
              style={{
                ...cellStyle,
                textAlign: "right",
                fontWeight: "bold",
                whiteSpace: "nowrap",
              }}
            >
              {formatPrice(balanceAmount, currentCurrency, false)}
            </td>
          </tr> */}
        </tbody>
      </table>

      {/* terms */}
      {/* <div style={{ paddingTop: "10px", marginTop: "-30px" }}>
        <table
          style={{
            width: "55%",
            border: "1px solid #000",
            borderCollapse: "collapse",
          }}
        >
          <thead>
            <tr>
              <th
                style={{
                  background: brandSettings?.primary_color,
                  color: "#fff",
                  fontWeight: 700,
                  padding: "5px",
                  fontSize: "13px",
                  border: "1px solid #000",
                  textAlign: "left",
                }}
              >
                TERMS AND CONDITIONS
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td
                style={{
                  padding: "10px",
                  border: "1px solid #000",
                  verticalAlign: "top",
                }}
              >
                <div
                  style={{
                    padding: "5px",
                    minHeight: "80px",
                    fontSize: "11px",
                    lineHeight: "1.2",
                  }}
                >
                  <div
                    className="overflow-hidden"
                    dangerouslySetInnerHTML={{
                      __html: form?.terms || settings?.terms_conditions || "",
                    }}
                  />
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div> */}

      {/* Signature Section */}
      <table style={{ width: "100%", marginTop: "30px" }}>
        <tbody>
          <tr>
            <td
              style={{
                width: "50%",
                verticalAlign: "top",
                borderBottom: "2px solid #000",
              }}
            >
              <div style={{ marginBottom: "60px" }}>
                {/* <div style={{ fontSize: "10px", marginBottom: "5px" }}>
                  Product or Services Received in Good Condition as described.
                </div> */}
                <div
                  style={{
                    borderTop: "1px solid #000",
                    marginTop: "40px",
                    paddingTop: "15px",
                    fontSize: "10px",
                  }}
                >
                  <strong>Signature:</strong>
                  {form?.digital_signature ? (
                    <img
                      src={`${apiUrl}/proxy?fileUrl=${frontEndUrl}${currentSession?.user?.digital_signature}`}
                      alt="Signature"
                      className="size-[120px] mb-[10px] object-contain"
                    />
                  ) : (
                    ""
                  )}
                </div>
                <div style={{ marginTop: "5px", fontSize: "10px" }}>
                  <strong>Received by :</strong>
                </div>
                <div style={{ marginTop: "5px", fontSize: "10px" }}>
                  <strong>Designation:</strong>
                </div>
                <div
                  style={{
                    textAlign: "right",
                    paddingRight: "60px",
                  }}
                >
                  {brandSettings?.company_name}
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td colSpan="2" style={{ marginTop: "50px", paddingTop: "20px" }}>
              <div
                style={{
                  textAlign: "center",
                  fontStyle: "italic",
                  fontWeight: "700",
                }}
              >
                Thank you for your business. Hope to serve you again.
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Helper Styles
const cellStyle = {
  border: "1px solid #000",
  padding: "6px 6px",
  fontSize: "10px",
  verticalAlign: "top",
};
