import { forwardRef } from "react";
import { type OrderLabelPayload } from "@/lib/orders/order-label-print";
import { formatDateBr } from "@/utils/formatters";

type OrderLabelPreviewProps = {
  payload: OrderLabelPayload;
  qrCodeDataUrl: string;
};

function formatMoney(value: number | string | null | undefined) {
  const parsed = Number(value);
  const num = Number.isFinite(parsed) ? parsed : 0;
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
  }).format(num);
}

function formatDate(value: string | null | undefined) {
  if (!value) return "-";
  return formatDateBr(value) || "-";
}

function normalizeText(value: string | null | undefined) {
  return (value || "").replace(/\s+/g, " ").trim();
}

function firstNonEmpty(...values: Array<string | null | undefined>) {
  for (const value of values) {
    const normalized = normalizeText(value);
    if (normalized) return normalized;
  }
  return "";
}

function onlyDigits(value: string | null | undefined) {
  return (value || "").replace(/\D/g, "");
}

function formatPhone(value: string | null | undefined) {
  const digits = onlyDigits(value);
  if (digits.length === 11) return digits.replace(/(\d{2})(\d{5})(\d{4})/, "+55 $1 $2-$3");
  if (digits.length === 10) return digits.replace(/(\d{2})(\d{4})(\d{4})/, "+55 $1 $2-$3");
  return (value || "").trim();
}

function buildAddress(client?: OrderLabelPayload["client"]) {
  if (!client) return "";
  const line1 = [client.addressStreet, client.addressNumber, client.addressComplement]
    .map((value) => normalizeText(value))
    .filter(Boolean)
    .join(", ");
  const line2 = [client.addressNeighborhood, client.addressCity, client.addressState]
    .map((value) => normalizeText(value))
    .filter(Boolean)
    .join(" - ");
  const zip = normalizeText(client.addressZip);
  return [line1, line2, zip ? `CEP ${zip}` : ""].filter(Boolean).join(" | ");
}

function financialStatusLabel(value: string | null | undefined) {
  const normalized = String(value || "").toLowerCase();
  if (normalized === "paid") return "Pago";
  if (normalized === "partially_paid") return "Parcial";
  if (normalized === "unpaid") return "Nao pago";
  return "Aberto";
}

function paymentSummary(payload: OrderLabelPayload) {
  const total = Number(payload.order.totalAmount) || 0;
  const paid = Number(payload.order.paidAmount) || 0;
  const status = (payload.order.financialStatus || "").toLowerCase();

  // Tratamento inteligente do status de pagamento
  if (status === "paid" || (total > 0 && paid >= total)) return "Totalmente Pago";
  if (status === "partially_paid" || (paid > 0 && paid < total)) {
    return `Sinal: ${formatMoney(paid)}`;
  }
  
  return "Aguardando Pag.";
}

export const OrderLabelPreview = forwardRef<HTMLDivElement, OrderLabelPreviewProps>(
  ({ payload, qrCodeDataUrl }, ref) => {
    const companyName = firstNonEmpty(payload.company?.name, "Empresa");
    const clientPrimaryName = firstNonEmpty(payload.client?.companyName, payload.client?.name, "Cliente");
    const clientSecondaryName =
      payload.client?.companyName && payload.client?.name && payload.client.name !== payload.client.companyName
        ? normalizeText(payload.client.name)
        : normalizeText(payload.client?.document);
    
    const phone = firstNonEmpty(
      formatPhone(payload.client?.whatsapp),
      formatPhone(payload.client?.phone),
      formatPhone(payload.company?.whatsapp),
      formatPhone(payload.company?.phone)
    );
    const address = buildAddress(payload.client);
    const observations = firstNonEmpty(
      payload.order.notes,
      payload.quote?.notes,
      payload.client?.notes,
      "Sem observacoes"
    );
    const orderNumber = String(payload.order.number || payload.order.id.slice(0, 8)).trim();
    const orderDate = formatDate(payload.order.createdAt);
    const payment = paymentSummary(payload);
    const totalText = formatMoney(payload.order.totalAmount);
    const logoUrl = normalizeText(payload.company?.logoUrl);

    return (
      <div
        ref={ref}
        style={{
          width: "400px",
          height: "282px",
          backgroundColor: "#ffffff",
          fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
          color: "#1d1d1f",
          border: "2px solid #2e176d",
          boxSizing: "border-box",
          display: "flex",
          position: "relative",
          overflow: "hidden",
        }}
      >
        {/* Left Strip */}
        <div
          style={{
            width: "40px",
            borderRight: "1px solid #cfc8ea",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "16px 0",
            flexShrink: 0,
            overflow: "hidden",
          }}
        >
          <div
            style={{
              transform: "rotate(-90deg)",
              fontSize: "16px",
              fontWeight: 800,
              letterSpacing: "0.15em",
              color: "#4425a7",
              textTransform: "uppercase",
              whiteSpace: "nowrap",
            }}
          >
            Pedido #{orderNumber}
          </div>
        </div>

        {/* Main Content */}
        <div style={{ flex: 1, padding: "12px 16px", display: "flex", flexDirection: "column", justifyContent: "space-between", minWidth: 0, overflow: "hidden" }}>
          {/* Header Row */}
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "12px", minHeight: "84px" }}>
            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: "12px", minWidth: 0, overflow: "hidden" }}>
              {logoUrl && (
                <img src={logoUrl} alt="Logo" style={{ height: "48px", width: "auto", maxWidth: "120px", objectFit: "contain", flexShrink: 0 }} />
              )}
              <div style={{ fontSize: "20px", color: "#5f6675", fontWeight: 800, lineHeight: 1.2, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", wordBreak: "break-word" }}>
                {companyName}
              </div>
            </div>
            <div style={{ width: "84px", height: "84px", flexShrink: 0 }}>
              <img src={qrCodeDataUrl} alt="QR Code" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
            </div>
          </div>

          {/* Client Name */}
          <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", minHeight: 0, paddingTop: "4px", paddingBottom: "10px" }}>
            <div style={{ fontSize: "9px", fontWeight: 700, color: "#4425a7", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: "4px", flexShrink: 0 }}>
              Nome
            </div>
            
            <div style={{ 
              display: "flex", 
              flexDirection: "column",
              justifyContent: "center",
              flex: 1,
              width: "100%",
            }}>
              <div style={{
                fontSize: clientPrimaryName.length > 40 ? "13px" : clientPrimaryName.length > 25 ? "15px" : "18px",
                fontWeight: 800,
                color: "#1d1d1f",
                lineHeight: 1.15,
                letterSpacing: "-0.02em",
                display: "-webkit-box",
                WebkitLineClamp: 3,
                WebkitBoxOrient: "vertical",
                overflow: "hidden",
                textOverflow: "ellipsis",
                width: "100%",
                wordBreak: "break-word"
              }}>
                {clientPrimaryName}
              </div>
            </div>
          </div>

          {/* Info Rows */}
          <div style={{ borderTop: "1px solid #cfc8ea", borderBottom: "1px solid #cfc8ea", padding: "8px 0", display: "flex", flexDirection: "column", gap: "6px", flexShrink: 0 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
              <div style={{ fontSize: "12px", fontWeight: 700, color: "#4425a7", width: "65px", flexShrink: 0 }}>
                Telefone
              </div>
              <div style={{ fontSize: "11px", color: "#1d1d1f", paddingTop: "1px" }}>{phone || "-"}</div>
            </div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
              <div style={{ fontSize: "12px", fontWeight: 700, color: "#4425a7", width: "65px", flexShrink: 0 }}>
                Endereço
              </div>
              <div style={{ fontSize: "11px", color: "#1d1d1f", paddingTop: "1px", lineHeight: 1.3, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{address || "-"}</div>
            </div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
              <div style={{ fontSize: "12px", fontWeight: 700, color: "#4425a7", width: "65px", flexShrink: 0 }}>
                Obs.
              </div>
              <div style={{ fontSize: "11px", color: "#1d1d1f", paddingTop: "1px", lineHeight: 1.3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{observations}</div>
            </div>
          </div>

          {/* Footer Grid */}
          <div style={{ display: "flex", gap: "8px", flexShrink: 0 }}>
            <div style={{ flex: 1, minWidth: 0, overflow: "hidden" }}>
              <div style={{ fontSize: "9px", fontWeight: 700, color: "#4425a7", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "2px" }}>
                Pagamento
              </div>
              <div style={{ fontSize: "11px", fontWeight: 700, color: "#1d1d1f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                {payment}
              </div>
            </div>
            <div style={{ borderLeft: "1px solid #cfc8ea", paddingLeft: "8px", flexShrink: 0, minWidth: "75px" }}>
              <div style={{ fontSize: "9px", fontWeight: 700, color: "#4425a7", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "2px" }}>
                Total
              </div>
              <div style={{ fontSize: "11px", fontWeight: 800, color: "#1d1d1f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                {totalText}
              </div>
            </div>
            <div style={{ borderLeft: "1px solid #cfc8ea", paddingLeft: "8px", flexShrink: 0, minWidth: "65px" }}>
              <div style={{ fontSize: "9px", fontWeight: 700, color: "#4425a7", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "2px" }}>
                Data
              </div>
              <div style={{ fontSize: "11px", fontWeight: 700, color: "#1d1d1f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                {orderDate}
              </div>
            </div>
          </div>
        </div>

        {/* Right Strip (Company Contact Info) */}
        <div
          style={{
            width: "28px",
            borderLeft: "1px solid #cfc8ea",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "16px 0",
            flexShrink: 0,
            overflow: "hidden",
          }}
        >
          <div
            style={{
              transform: "rotate(-90deg)",
              fontSize: "8px",
              fontWeight: 700,
              color: "#4425a7",
              whiteSpace: "nowrap",
              letterSpacing: "0.05em",
            }}
          >
            ACESSE ESSE PEDIDO COMPLETO LENDO O QR CODE
          </div>
        </div>
      </div>
    );
  }
);

OrderLabelPreview.displayName = "OrderLabelPreview";
