import { SHOP_INFO, COMPANY_POLICY, INVOICE_DEFAULTS } from "@/Utils/constants";
import React from "react";
import { toWords } from "number-to-words";

function PurchaseMakerPrint({ list, info }) {
  if (!list || Object.keys(list).length === 0) {
    return null; // Don't render anything if no data is provided
  }

  // Helper to safely get product attribute with fallbacks
  const getProductAttribute = (item) => {
    return item.product_attribute || item.productAttribute || null;
  };

  // Helper to safely get nested relationship value
  const getAttrValue = (attr, relationshipName) => {
    if (!attr) return null;
    // Try both snake_case and camelCase
    const rel = attr[relationshipName] || attr[relationshipName.replace(/_/g, (m, i) => i === 0 ? '' : m.charAt(1).toUpperCase() + m.slice(2))];
    return rel?.name || null;
  };

  const parsePcsFromConversionInput = (conversionInput) => {
    if (!conversionInput) return null;
    const parts = String(conversionInput)
      .split(",")
      .map((p) => p.trim())
      .filter(Boolean);
    const pcs = parseFloat(parts[2]);
    return Number.isFinite(pcs) && pcs > 0 ? pcs : null;
  };

  // Format date function
  const formatDate = (dateString) => {
    if (!dateString) return "N/A";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

  return (
    <div className="bg-gray-100 p-10 text-sm text-gray-900 font-sans hidden print:block">
      <div className="w-full bg-white">
        {/* Header */}
        <table className="w-full mb-6">
          <tbody>
            <tr>
              <td className="w-1/2 align-top">
                <h1 className="text-2xl font-bold mb-2">
                  {SHOP_INFO.name}
                </h1>
                <p>{SHOP_INFO.address}</p>
                <p>Email: {SHOP_INFO.email}</p>
                <p>Phone: {SHOP_INFO.phone}</p>
              </td>
              <td className="w-1/2 text-right align-top">
                <h2 className="text-xl font-semibold">
                  PURCHASE ORDER
                </h2>
                <p className="mt-2">
                  PO #: <strong>{list.po_no || "N/A"}</strong>
                  <br />
                  Date:{" "}
                  <strong>{formatDate(list.po_date)}</strong>
                  <br />
                </p>
              </td>
            </tr>
          </tbody>
        </table>

        {/* Supplier / Ship To */}
        <table className="w-full mb-6">
          <tbody>
            <tr>
              {list.supplier && (
                <td className="w-1/2 align-top">
                  <h3 className="font-semibold mb-2">
                    Supplier
                  </h3>
                  <p>{list.supplier?.name || "N/A"}</p>
                  <p>{list.supplier?.address || ""}</p>
                  <p>
                    Email: {list.supplier?.email || "N/A"}
                  </p>
                  <p>
                    Phone: {list.supplier?.number || "N/A"}
                  </p>
                </td>
              )}

              <td className="w-1/2 align-top text-right">
                <h3 className="font-semibold mb-2">Ship To</h3>
                <p>{SHOP_INFO.name}</p>
                <p>{SHOP_INFO.address}</p>
              </td>
            </tr>
          </tbody>
        </table>

        {/* Items Table */}
        <table className="w-full border border-gray-300 mb-6">
          <thead className="bg-gray-100 text-xs uppercase text-gray-700">
            <tr>
              <th className="border px-3 py-2 text-left">#</th>
              <th className="border px-3 py-2 text-left">
                Product
              </th>
              <th className="border px-3 py-2 text-right">Cartton/Box</th>
              <th className="border px-3 py-2 text-right">Qty (pcs)</th>

              <th className="border px-3 py-2 text-right">
                Unit Price
              </th>
              <th className="border px-3 py-2 text-right">
                Get Qty
              </th>
            </tr>
          </thead>
          <tbody>
            {true ? (
              list.details.map((item, index) => (
                <tr key={index}>
                  <td className="border px-3 py-2">
                    {index + 1}
                  </td>
                  <td className="border px-3 py-2">
                    <div className="font-medium text-gray-800">
                      {item.product_info?.name || "N/A"}
                    </div>
                    {(() => {
                      const attr = getProductAttribute(item);
                      if (!attr) return null;

                      const productType = getAttrValue(attr, 'product_type') || getAttrValue(attr, 'productType');
                      const size = getAttrValue(attr, 'size');
                      const color = getAttrValue(attr, 'color');
                      const model = getAttrValue(attr, 'model');
                      const goldUnit = getAttrValue(attr, 'gold_unit') || getAttrValue(attr, 'goldUnit');
                      const goldWeight = attr.gold_weight;
                      const diamondUnit = getAttrValue(attr, 'diamond_unit') || getAttrValue(attr, 'diamondUnit');
                      const diamondWeight = attr.diamond_weight;
                      const brand = getAttrValue(attr, 'brand');
                      const origin = getAttrValue(attr, 'origin');

                      return (
                        <>
                          {/* SKU badge */}
                          {attr.sku && (
                            <div className="mt-1">
                              <span className="text-[10px] text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-sm font-normal inline-block">
                                SKU: {attr.sku}
                              </span>
                            </div>
                          )}
                          {/* Product attributes - similar to POS product search */}
                          <div className="text-[10px] text-gray-600 mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                            {productType && <span>{productType}</span>}
                            {size && <span>• {size}</span>}
                            {color && <span>• {color}</span>}
                            {model && <span>• {model}</span>}
                            {goldUnit && goldWeight && (
                              <span className="text-amber-700">
                                • Gold <b>{goldWeight}</b> {goldUnit}
                              </span>
                            )}
                            {diamondUnit && diamondWeight && (
                              <span className="text-blue-700">
                                • Dia <b>{diamondWeight}</b> {diamondUnit}
                              </span>
                            )}
                            {brand && <span className="text-gray-500">• {brand}</span>}
                            {origin && <span>• Origin: {origin}</span>}
                          </div>
                        </>
                      );
                    })()}
                  </td>
                  <td className="border px-3 py-2 text-right">
                    {item.carton_box ?? ""}

                  </td>
                  <td className="border px-3 py-2 text-right">
                    {item.quantity || 0}{" "}
                    {(() => {
                      const attr = item.product_attribute || item.productAttribute;
                      return attr?.unit?.name || "pcs";
                    })()}
                  </td>

                  <td className="border px-3 py-2 text-right"></td>
                  <td className="border px-3 py-2 text-right"></td>
                </tr>
              ))
            ) : (
              <tr>
                <td
                  colSpan="5"
                  className="border px-3 py-2 text-center"
                >
                  No items available
                </td>
              </tr>
            )}
          </tbody>
        </table>

        {/* Signatures */}
        <table className="w-full mt-10">
          <tbody>
            <tr>
              <td className="w-1/2 text-left">
                <p className="mb-1">
                  _________________________
                </p>
                <p className="text-gray-600">
                  Authorized Signature
                </p>
              </td>
              <td className="w-1/2 text-right">
                <p className="mb-1">
                  _________________________
                </p>
                <p className="text-gray-600">
                  Supplier Signature
                </p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default PurchaseMakerPrint;
