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";

/**
 * 2 inch (58mm) Customer slip – page setup for 2 inch thermal.
 */
function Print2InchCustomer({ sales, auth }) {
  const { permission } = useContext(authUser);

  const safeNumber = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);

  const formatItemDescription = (item) => {
    const name =
      item?.product?.name ??
      item?.attribute?.product?.name ??
      item?.arribute?.product?.name ??
      item?.name ??
      item?.product_name ??
      "";
    return name || "—";
  };

  const sale = sales && typeof sales === "object" && !Array.isArray(sales) ? sales : {};
  const details = Array.isArray(sale.details) ? sale.details : [];

  const invoiceNumber = sale?.invoice_no ?? "";
  const date = sale?.created_at
    ? new Date(sale.created_at).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      timeZone: "UTC",
    })
    : "—";

  const company = {
    name: SHOP_INFO.name,
    address: SHOP_INFO.address,
    email: SHOP_INFO.email,
    phone: SHOP_INFO.phone,
    slogan: SHOP_INFO.slogan,
  };

  const customer = {
    name: sale?.customer?.name,
    address: sale?.customer?.address,
    phone: sale?.customer?.number,
    email: sale?.customer?.email,
    code: sale?.customer?.code,
  };

  const tableName =
    sale?.table?.name ??
    sale?.table?.label ??
    sale?.table_name ??
    sale?.order_type ??
    "";
  const orderSlot = sale?.order_slot ?? null;
  const tableOrderKey =
    sale?.table_order_key ??
    (tableName && orderSlot ? `${tableName} #${orderSlot}` : null);

  const items = details.map((item) => {
    const qty = safeNumber(item?.qty ?? item?.quantity ?? 1);
    const price =
      safeNumber(item?.price) ||
      safeNumber(item?.mrp_price) ||
      safeNumber(item?.tp_price) ||
      0;
    const total = safeNumber(item?.total) || price * qty;
    return {
      description: formatItemDescription(item),
      sku: item?.arribute?.sku ?? item?.attribute?.sku ?? item?.sku ?? "",
      quantity: qty,
      price,
      total,
    };
  });

  const totals = {
    subtotal: safeNumber(sale?.total),
    discount: safeNumber(sale?.discount),
    discount_2nd: safeNumber(sale?.discount_second),
    after_discount: safeNumber(sale?.after_discount),
    total: safeNumber(sale?.grand_total ?? sale?.total),
    previous_due: safeNumber(sale?.previous_due),
    payment: safeNumber(sale?.current_payment),
    order: sale?.order_no ?? "N/A",
    transition_location: sale?.transition_location?.name ?? "N/A",
  };

  const words = (() => {
    const w = toWords((safeNumber(totals.total) || 0).toFixed(2));
    return w ? String(w).charAt(0).toUpperCase() + String(w).slice(1) : "";
  })();

  return (
    <div className="customer-slip-print print-2inch mx-auto break-after-avoid-page hidden print:!block print:bg-white print:relative" style={{ width: "58mm", maxWidth: "58mm" }}>
      <style>{`
        @media print {
          @page { size: 58mm auto; margin: 0; padding: 0; }
          body { margin: 0; padding: 0; }
          .print-2inch { width: 220px !important; max-width: 220px !important; min-width: 220px !important; font-size: 13px !important; overflow: visible !important; color: #000 !important; }
          .print-2inch * { overflow: visible !important; color: inherit !important; }
          .print-2inch p, .print-2inch span, .print-2inch div { color: #000 !important; font-weight: 500 !important; }
          .print-2inch .font-semibold, .print-2inch .font-bold { font-weight: 700 !important; }
          .print-2inch .font-medium { font-weight: 600 !important; }
          .customer-slip-print { display: block !important; visibility: visible !important; }
        }
        @media print and (max-width: 768px) {
          .print-2inch { width: 220px !important; max-width: 220px !important; min-width: 220px !important; box-sizing: border-box !important; }
        }
      `}</style>

      <div className="print-2inch text-center py-1.5 border-b-2 border-gray-800">
        {SHOP_INFO.companyLogo && (
          <img src={SHOP_INFO.companyLogo || defaultLogo} alt="Logo" className="w-10 h-10 mx-auto mb-1 object-contain" />
        )}
        <h2 className="text-[14px] font-bold uppercase tracking-wide leading-tight">{company.name}</h2>
        {company.slogan && <p className="text-[13px] text-gray-600 italic mt-0.5">{company.slogan}</p>}
        <p className="text-[13px] text-gray-700 leading-tight mt-0.5">{company.address}</p>
        <p className="text-[13px] text-gray-700 mt-0.5">Ph: {company.phone} | {company.email}</p>
      </div>

      <div className="print-2inch text-center py-1.5 border-b-2 border-green-600 bg-green-50/80">
        <h3 className="text-[13px] font-bold uppercase tracking-wider text-green-800">CUSTOMER COPY</h3>
      </div>

      <div className="print-2inch text-center py-1 border-b border-gray-400">
        <h3 className="text-[13px] font-bold uppercase tracking-wider">INVOICE</h3>
        <div className="text-[13px] mt-0.5 space-y-0.5">
          <p><span className="font-semibold">Date:</span> {date}</p>
          {invoiceNumber ? <p><span className="font-semibold">Inv#:</span> {invoiceNumber}</p> : null}
          {tableOrderKey && (
            <p><span className="font-semibold">Slot No.:</span> {tableOrderKey}</p>
          )}
          {permission?.includes?.("sales_order_view") && totals.order !== "N/A" && (
            <p><span className="font-semibold">Order#:</span> {totals.order}</p>
          )}
        </div>
      </div>

      {customer?.name && (
        <div className="print-2inch py-1 border-b border-gray-300 text-[13px]">
          <p className="font-bold">Customer: {customer.name}</p>
          {customer.code && <p>ID: {customer.code}</p>}
          {customer.phone && <p>Ph: {customer.phone}</p>}
          {customer.address && <p className="leading-tight">{customer.address}</p>}
        </div>
      )}

      <div className="print-2inch py-1">
        <p className="text-[12px] font-bold uppercase mb-0.5 border-b border-gray-400 pb-0.5">Items</p>
        <div className="text-[13px] font-semibold grid grid-cols-12 gap-0.5 py-0.5 border-b border-gray-400">
          <div className="col-span-5">Item</div>
          <div className="col-span-2 text-center">Qty</div>
          <div className="col-span-2 text-center">Pr</div>
          <div className="col-span-3 text-right">Total</div>
        </div>

        {items.length === 0 ? (
          <p className="text-[12px] text-gray-500 py-1">No items</p>
        ) : (
          items.map((item, index) => (
            <div key={index} className="border-b border-gray-200 py-0.5 text-[12px]">
              <div className="grid grid-cols-12 gap-x-0.5 items-baseline">
                <div className="col-span-5 min-w-0 overflow-visible">
                  <p className="font-medium leading-tight break-words">{item.description}</p>
                  {item.sku && <p className="text-[10px] text-gray-600">SKU: {item.sku}</p>}
                </div>
                <div className="col-span-2 text-center">{item.quantity}</div>
                <div className="col-span-2 text-center">{safeNumber(item.price).toFixed(2)}</div>
                <div className="col-span-3 text-right font-semibold">{safeNumber(item.total).toFixed(2)}</div>
              </div>
            </div>
          ))
        )}
      </div>

      <div className="print-2inch border-t-2 border-gray-600 pt-1 mt-1">
        <div className="text-[12px] space-y-0.5">
          <div className="flex justify-between">
            <span>Sub-Total:</span>
            <span className="font-semibold">{safeNumber(totals.subtotal).toFixed(2)}</span>
          </div>
          {(safeNumber(totals.discount) || 0) > 0 && (
            <div className="flex justify-between">
              <span>Discount:</span>
              <span>{safeNumber(totals.discount).toFixed(2)}</span>
            </div>
          )}
          <div className="flex justify-between border-t border-gray-400 pt-0.5 mt-0.5 font-bold text-[13px]">
            <span>Total:</span>
            <span>{safeNumber(totals.total).toFixed(2)}</span>
          </div>
          {permission?.includes?.("sales_invoice_due_view") && (
            <>
              <div className="flex justify-between border-t border-gray-300 pt-0.5">
                <span>Payment:</span>
                <span>{safeNumber(totals.payment).toFixed(2)}</span>
              </div>
              <div className="flex justify-between">
                <span>Due:</span>
                <span className="font-semibold">
                  {(safeNumber(totals.total) - safeNumber(totals.payment)).toFixed(2)}
                </span>
              </div>
            </>
          )}
        </div>
      </div>

      <div className="print-2inch border-t border-gray-300 pt-1 mt-1">
        <p className="text-[13px] leading-tight">
          <span className="font-semibold">In Words:</span> {words}
        </p>
      </div>

      {INVOICE_DEFAULTS.footerNote && (
        <div className="print-2inch border-t border-gray-300 pt-1 mt-1">
          <p className="text-[10px] text-gray-600 leading-tight text-center">
            <span className="font-semibold">NB:</span> {INVOICE_DEFAULTS.footerNote}
          </p>
        </div>
      )}

      <div className="print-2inch text-center py-1.5 mt-1 border-t border-gray-300">
        <p className="text-[13px] font-bold">Thank You!</p>
        <p className="text-[10px] text-gray-500 mt-0.5">Powered by DATA DSS LTD</p>
      </div>
    </div>
  );
}

export default Print2InchCustomer;
