import React, { useContext } from "react";
import Barcode from "react-barcode";
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";

function Print3Inch({ sales, auth }) {
  const { permission } = useContext(authUser);
  const posTableParcelData =
    typeof sales?.pos_table_parcel_json === "string"
      ? (() => {
          try {
            return JSON.parse(sales.pos_table_parcel_json);
          } catch {
            return null;
          }
        })()
      : sales?.pos_table_parcel_json;
  const tableOrParcel = posTableParcelData?.table_or_parcel ?? "";
  const normalizedType = String(tableOrParcel || "").toLowerCase();
  const serviceTypeLabel =
    normalizedType === "table"
      ? "Dine In"
      : normalizedType === "parcel"
        ? "Parcel"
        : tableOrParcel;

  const formatItemDescription = (item) => {
    const name = item?.product?.name ?? item?.attribute?.product?.name ?? "";
    const gold = item?.arribute?.gold_unit?.name || item?.attribute?.gold_unit?.name
      ? ` | Gold: ${item?.arribute?.gold_weight ?? item?.attribute?.gold_weight ?? 0} ${item?.arribute?.gold_unit?.name || item?.attribute?.gold_unit?.name}`
      : "";
    const diamond = item?.arribute?.diamond_unit?.name || item?.attribute?.diamond_unit?.name
      ? ` | Diamond: ${item?.arribute?.diamond_weight ?? item?.attribute?.diamond_weight ?? 0} ${item?.arribute?.diamond_unit?.name || item?.attribute?.diamond_unit?.name}`
      : "";
    return `${name}${gold}${diamond}`;
  };

  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",
    }),
    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: formatItemDescription(item),
        sku: item?.arribute?.sku ?? item?.attribute?.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 ?? item?.attribute?.size?.name ?? "N/A",
        fqty: item.fqty ?? 0,
        allData: item,
      })) || [],
    exchangeItems:
      sales?.exchange_return?.details?.map((item) => ({
        description: formatItemDescription(item),
        sku: item?.attribute?.sku ?? "",
        quantity: item.return_qty ?? 0,
        price: Number(item.return_price ?? item.sales_price ?? 0),
        total: Number(item.total ?? 0),
      })) || [],
    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: Number(sales.previous_due || 0),
      payment: Number(sales.current_payment || 0),
      order: sales.order_no || "N/A",
      transition_location: sales?.transition_location?.name || "N/A",
      createdBy: sales?.user?.name || sales?.User?.name || "N/A",
      tableOrParcel,
    },
  };

  const { invoiceNumber, date, company, customer, items, exchangeItems, totals } = invoiceData;
  const isExchange = exchangeItems.length > 0;

  return (
    <div className="w-[80mm] max-w-[80mm] mx-auto break-after-avoid-page hidden print:bg-white print:relative print:block print:w-[80mm]">
      <style>{`
                @media print {
                    @page { size: 80mm auto; margin: 0; padding: 0; }
                    body { margin: 0; padding: 0; }
                    .print-3inch { width: 80mm !important; max-width: 80mm !important; font-size: 12px !important; color: #000 !important; }
                    .print-3inch * { color: inherit !important; }
                    .print-3inch p, .print-3inch span, .print-3inch div { color: #000 !important; font-weight: 500 !important; }
                    .print-3inch .font-semibold, .print-3inch .font-bold { font-weight: 700 !important; }
                    .print-3inch .font-medium { font-weight: 600 !important; }
                    .print-row { display: flex; justify-content: space-between; align-items: flex-start; gap: 4px; }
                    .print-invoice-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 8px; align-items: baseline; }
                }
            `}</style>

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

      {/* Invoice Title - 2×2 grid, minimal height */}
      <div className="print-3inch py-0.5 border-b border-gray-400">
        <h3 className="text-[12px] font-bold uppercase tracking-wider text-center">INVOICE</h3>
        <div className="text-[11px] print-invoice-grid mt-0.5">
          <div className="print-row">
            <span className="font-semibold text-gray-900">Date</span>
            <span className="font-semibold">{date}</span>
          </div>
          <div className="print-row">
            <span className="font-semibold text-gray-900">Inv#</span>
            <span className="font-semibold">{invoiceNumber}</span>
          </div>
          <div className="print-row">
            <span className="font-semibold text-gray-900">Created By</span>
            <span className="font-semibold">{totals.createdBy}</span>
          </div>
          <div className="print-row">
            <span className="font-semibold text-gray-900">Customer</span>
            <span className="font-semibold">{customer?.phone || "—"}</span>
          </div>
          {totals.tableOrParcel ? (
            <div className="print-row">
              <span className="font-semibold text-gray-900">Service</span>
              <span className="font-semibold">{serviceTypeLabel || "-"}</span>
            </div>
          ) : null}
          {/* {((permission.includes("sales_order_view") && totals.order !== "N/A") || permission.includes("sales_person_pos_view")) && (
            <div className="print-row">
              <span className="text-gray-600">
                {permission.includes("sales_order_view") && totals.order !== "N/A" && permission.includes("sales_person_pos_view") ? "Order · Sales" : permission.includes("sales_order_view") && totals.order !== "N/A" ? "Order" : "Sales"}
              </span>
              <span>
                {permission.includes("sales_order_view") && totals.order !== "N/A" && totals.order}
                {permission.includes("sales_order_view") && totals.order !== "N/A" && permission.includes("sales_person_pos_view") && " · "}
                {permission.includes("sales_person_pos_view") && totals.transition_location}
              </span>
            </div>
          )} */}
        </div>
      </div>

      {/* Customer details (phone, address) - optional block */}
      {/* {customer.phone && (
        <div className="print-3inch py-0.5 border-b border-gray-300 text-[9px]">
          {customer.code && <p>ID: {customer.code}</p>}
          {customer.phone && <p>Ph: {customer.phone}</p>}
          {customer.address && <p className="leading-tight">{customer.address}</p>}
        </div>
      )} */}

      {/* Exchange Returned Items (if exchange invoice) */}
      {isExchange && (
        <div className="print-3inch py-1 border-b-2 border-amber-500 bg-amber-50/50">
          <p className="text-[10px] font-bold uppercase text-amber-800 mb-0.5">
            Exchanged Out (Returned)
          </p>
          {exchangeItems.map((item, idx) => (
            <div key={idx} className="text-[9px] py-0.5 border-b border-amber-200 last:border-0 flex justify-between items-baseline gap-2">
              <div className="min-w-0">
                <p className="font-semibold leading-tight">{item.description}</p>
                {item.sku && <p className="text-[11px] font-semibold text-gray-900">SKU: {item.sku}</p>}
              </div>
              <span className="shrink-0 whitespace-nowrap">
                {item.quantity} × {item.price.toFixed(2)} = {item.total.toFixed(2)}
              </span>
            </div>
          ))}
        </div>
      )}

      {/* Sold Items */}
      <div className="print-3inch py-1">
        <p className="text-[10px] font-bold uppercase mb-0.5 border-b border-gray-400 pb-0.5">
          {isExchange ? "Exchanged In (New Items)" : "Items"}
        </p>
        <div className="text-[10px] 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">Price</div>
          <div className="col-span-3 text-right">Total</div>
        </div>

        {items.map((item, index) => (
          <div key={index} className="border-b border-gray-200 py-0.5 text-[11px]">
            <div className="grid grid-cols-12 gap-x-1 items-baseline">
              <div className="col-span-5 min-w-0">
                <p className="font-semibold leading-tight">{item.description}</p>
                <div className="text-[11px] font-semibold text-gray-900 leading-tight">
                  {item.sku && `SKU: ${item.sku}`}
                  {item.sku && item?.allData?.arribute?.brand?.name && " | "}
                  {item?.allData?.arribute?.brand?.name && `Brand: ${item.allData.arribute.brand.name}`}
                  {item?.allData?.arribute?.size?.name && ` | Size: ${item.size}`}
                  {item?.warranty_code && ` | Warranty: ${item.warranty_code}`}
                </div>
              </div>
              <div className="col-span-2 text-center">{item.quantity}</div>
              <div className="col-span-2 text-center">{item.price.toFixed(2)}</div>
              <div className="col-span-3 text-right font-semibold">{item.total.toFixed(2)}</div>
            </div>
            {item?.after_discount_amount > 0 && (
              <p className="text-[11px] font-semibold text-gray-900">Disc: {Number(item.after_discount_amount || 0).toFixed(2)}</p>
            )}
          </div>
        ))}
      </div>

      {/* Totals */}
      <div className="print-3inch border-t-2 border-gray-600 pt-1 mt-1">
        <div className="text-[10px] space-y-0.5">
          <div className="flex justify-between">
            <span>Sub-Total:</span>
            <span className="font-semibold">{totals.subtotal.toFixed(2)}</span>
          </div>
          {totals.after_discount > 0 && (
            <div className="flex justify-between">
              <span>Discount:</span>
              <span>{totals.after_discount.toFixed(2)}</span>
            </div>
          )}
          <div className="flex justify-between border-t border-gray-400 pt-0.5 mt-0.5 font-bold text-[11px]">
            <span>Grand Total:</span>
            <span>{totals.total.toFixed(2)}</span>
          </div>
          <div className="flex justify-between border-t border-gray-300 pt-0.5">
            <span>Payment:</span>
            <span>{totals.payment.toFixed(2)}</span>
          </div>
          <div className="flex justify-between">
            <span>Due:</span>
            <span className="font-semibold">{(totals.total - totals.payment).toFixed(2)}</span>
          </div>

          {permission.includes("sales_invoice_due_view") && (
            <>

              {totals.previous_due > 0 && (
                <div className="flex justify-between text-[11px] font-semibold text-gray-900">
                  <span>Previous Due:</span>
                  <span>{totals.previous_due.toFixed(2)}</span>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {/* Amount in Words */}
      <div className="print-3inch border-t border-gray-300 pt-1 mt-1">
        <p className="text-[11px] font-semibold leading-tight text-gray-900">
          <span className="font-bold">In Words:</span>{" "}
          {totals.total
            ? toWords(totals.total.toFixed(2))[0].toUpperCase() + toWords(totals.total.toFixed(2)).slice(1)
            : ""}
        </p>
      </div>

      {/* Footer Note */}
      {INVOICE_DEFAULTS.footerNote && (
        <div className="print-3inch border-t border-gray-300 pt-1 mt-1">
          <p className="text-[11px] font-semibold text-gray-900 leading-tight text-center">
            <span className="font-bold">NB:</span> {INVOICE_DEFAULTS.footerNote}
          </p>
        </div>
      )}

      {/* Invoice footer: barcode of invoice number */}
      {invoiceNumber && (
        <div className="print-3inch border-t border-gray-300 pt-1 mt-1 flex flex-col items-center">
          <Barcode
            value={String(invoiceNumber)}
            width={1}
            height={24}
            fontSize={12}
            margin={0}
            displayValue={true}
          />
        </div>
      )}

      {/* Thank You */}
      <div className="print-3inch text-center py-2 mt-1 border-t border-gray-300">
        <p className="text-[11px] font-bold">Thank You!</p>
        <p className="text-[11px] font-semibold text-gray-900 mt-0.5">Powered by DATA DSS LTD</p>
        <p className="text-[11px] font-semibold text-gray-900">www.datadss.com</p>
      </div>
    </div>
  );
}

export default Print3Inch;
