import { useEffect } from 'react';
import { Button, Spin, Alert } from 'antd';
import { PrinterOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from '@tanstack/react-router';
import { SITUA_LABEL } from '@sar/api-interface';
import { useOrderDetail } from '../../lib/queries/orders';
import { useClientDetail } from '../../lib/queries/clients';
import { useCompany } from '../../lib/queries/company';

// ─── Paleta / tokens ────────────────────────────────────────────────────────
const BLUE = '#003B8E';
const INK = '#1F2937';
const MUTED = '#64748B';
const LINE = '#E5EAF0';

// ─── Helpers de formatação ──────────────────────────────────────────────────
function money(v: string | number | null | undefined): string {
  const n = typeof v === 'string' ? parseFloat(v) : (v ?? 0);
  return (isNaN(n as number) ? 0 : (n as number)).toLocaleString('pt-BR', {
    style: 'currency',
    currency: 'BRL',
  });
}
function qty(v: string | number): string {
  return Number(v).toLocaleString('pt-BR', { maximumFractionDigits: 3 });
}
function dateBR(v: string | null | undefined): string {
  return v ? new Date(v).toLocaleDateString('pt-BR') : '—';
}
function doc(raw: string | null | undefined): string {
  if (!raw) return '—';
  const d = raw.replace(/\D/g, '');
  if (d.length === 14) return d.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
  if (d.length === 11) return d.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
  return raw;
}
function phone(raw: string | null | undefined, ddd?: string | null): string {
  const d = `${ddd ?? ''}${raw ?? ''}`.replace(/\D/g, '');
  if (d.length === 11) return d.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
  if (d.length === 10) return d.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
  return raw ?? '—';
}
function cep(raw: string | null | undefined): string {
  const d = (raw ?? '').replace(/\D/g, '');
  return d.length === 8 ? d.replace(/(\d{5})(\d{3})/, '$1-$2') : (raw ?? '');
}
// Campos char do ERP vêm com padding — limpa, devolve null se vazio.
function tx(s: string | null | undefined): string | null {
  const t = (s ?? '').trim();
  return t === '' ? null : t;
}

// ─── Blocos visuais ─────────────────────────────────────────────────────────
const label: React.CSSProperties = {
  fontSize: 9,
  fontWeight: 700,
  letterSpacing: '0.08em',
  textTransform: 'uppercase',
  color: MUTED,
  display: 'block',
  marginBottom: 2,
};

export function OrderPrintPage() {
  const { id } = useParams({ from: '/pedidos/$id/imprimir' });
  const navigate = useNavigate();
  const { data: order, isLoading, error } = useOrderDetail(id);
  const { data: client } = useClientDetail(order?.idCliente);
  const { data: empresa } = useCompany();

  // Auto-abre o diálogo de impressão quando tudo carregou.
  useEffect(() => {
    if (order && empresa) {
      const t = setTimeout(() => window.print(), 600);
      return () => clearTimeout(t);
    }
  }, [order, empresa]);

  if (isLoading) return <Spin style={{ display: 'block', marginTop: 80 }} />;
  if (error || !order)
    return <Alert type="error" message="Pedido não encontrado." style={{ margin: 24 }} />;

  const enderecoCli = client
    ? [
        tx(client.endereco),
        tx(client.numEndereco),
        tx(client.bairro),
        client.cep ? `CEP ${cep(client.cep)}` : null,
      ]
        .filter(Boolean)
        .join(', ')
    : null;
  const cgDigits = (client?.cgcpf ?? '').replace(/\D/g, '').length;
  const docLabel = cgDigits === 11 ? 'CPF' : 'CNPJ';
  const enderecoEmp = empresa
    ? [empresa.endereco, empresa.numero, empresa.complemento, empresa.bairro]
        .filter(Boolean)
        .join(', ')
    : null;
  const cidadeEmp = empresa
    ? [empresa.cidade, empresa.uf].filter(Boolean).join(' - ') +
      (empresa.cep ? ` · CEP ${cep(empresa.cep)}` : '')
    : null;

  const clienteNome =
    tx(order.razaoCliente) ?? tx(order.nomeCliente) ?? `Cliente ${order.idCliente}`;
  const temDesc = Number(order.descontoValor) > 0 || Number(order.descontoPerc) > 0;

  return (
    <div style={{ background: '#EEF2F7', minHeight: '100vh', padding: '24px 0 60px' }}>
      {/* Barra de ações (não imprime) */}
      <div
        className="no-print"
        style={{
          maxWidth: 820,
          margin: '0 auto 16px',
          display: 'flex',
          justifyContent: 'space-between',
          padding: '0 8px',
        }}
      >
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate({ to: '/pedidos/$id', params: { id } })}
        >
          Voltar
        </Button>
        <Button type="primary" icon={<PrinterOutlined />} onClick={() => window.print()}>
          Imprimir / Salvar PDF
        </Button>
      </div>

      {/* Documento A4 */}
      <div
        className="sar-print"
        style={{
          width: '100%',
          maxWidth: 820,
          margin: '0 auto',
          background: '#fff',
          boxShadow: '0 4px 24px rgba(0,0,0,0.10)',
          borderRadius: 4,
          overflow: 'hidden',
          fontFamily: "'Plus Jakarta Sans Variable', system-ui, sans-serif",
          color: INK,
        }}
      >
        {/* ── Cabeçalho compacto: logo + empresa matriz + nº do pedido ────── */}
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            gap: 16,
            padding: '12px 28px',
            borderTop: `4px solid ${BLUE}`,
            borderBottom: `2px solid ${BLUE}`,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0 }}>
            {empresa?.logoBase64 && (
              <img
                src={empresa.logoBase64}
                alt="Logo"
                style={{ maxHeight: 52, maxWidth: 140, objectFit: 'contain', flexShrink: 0 }}
              />
            )}
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 800, color: BLUE, lineHeight: 1.15 }}>
                {empresa?.nomeFantasia ?? empresa?.razaoSocial ?? '...'}
              </div>
              <div style={{ fontSize: 8.5, color: MUTED, marginTop: 2, lineHeight: 1.45 }}>
                {empresa?.razaoSocial && empresa.razaoSocial !== empresa.nomeFantasia && (
                  <>{empresa.razaoSocial} · </>
                )}
                {empresa?.cnpj && <>CNPJ {empresa.cnpj}</>}
                {empresa?.inscricaoEstadual && <> · IE {empresa.inscricaoEstadual}</>}
                <br />
                {[enderecoEmp, cidadeEmp].filter(Boolean).join(' · ')}
                {(empresa?.telefone || empresa?.email) && (
                  <>
                    <br />
                    {empresa?.telefone && <>Tel {phone(empresa.telefone)}</>}
                    {empresa?.telefone && empresa?.email && <> · </>}
                    {empresa?.email}
                  </>
                )}
              </div>
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ fontSize: 9, color: MUTED, fontWeight: 700, letterSpacing: '0.1em' }}>
              PEDIDO
            </div>
            <div style={{ fontSize: 19, fontWeight: 800, color: INK, lineHeight: 1.1 }}>
              {order.numPedSar}
            </div>
            <div style={{ fontSize: 9.5, color: MUTED, marginTop: 3 }}>
              <span
                style={{
                  display: 'inline-block',
                  padding: '1px 8px',
                  borderRadius: 20,
                  background: `${BLUE}12`,
                  color: BLUE,
                  fontWeight: 700,
                  marginRight: 6,
                }}
              >
                {SITUA_LABEL[order.situa] ?? String(order.situa)}
              </span>
              {dateBR(order.dtPedido)}
            </div>
          </div>
        </div>

        {/* ── Representante + Cliente ─────────────────────────────────────── */}
        <div
          style={{
            display: 'flex',
            borderBottom: `1px solid ${LINE}`,
            background: '#FAFBFD',
          }}
        >
          {/* Representante */}
          <div
            style={{
              flex: 1,
              padding: '10px 20px 10px 28px',
              borderRight: `1px solid ${LINE}`,
            }}
          >
            <div
              style={{
                fontSize: 8.5,
                fontWeight: 800,
                color: BLUE,
                letterSpacing: '0.12em',
                textTransform: 'uppercase',
                marginBottom: 4,
              }}
            >
              Representante
            </div>
            <div style={{ fontSize: 12, fontWeight: 700, color: INK, lineHeight: 1.3 }}>
              {tx(order.nomeVendedor) ?? `Cód. ${order.codVendedor}`}
            </div>
            <div style={{ fontSize: 10, color: MUTED, marginTop: 2 }}>Cód. {order.codVendedor}</div>
          </div>

          {/* Cliente */}
          <div style={{ flex: 2.2, padding: '10px 28px 10px 20px' }}>
            <div
              style={{
                fontSize: 8.5,
                fontWeight: 800,
                color: BLUE,
                letterSpacing: '0.12em',
                textTransform: 'uppercase',
                marginBottom: 4,
              }}
            >
              Cliente
            </div>
            <div style={{ fontSize: 12, fontWeight: 700, color: INK, lineHeight: 1.3 }}>
              {clienteNome}
            </div>
            {tx(client?.nome) && tx(client?.razao) && tx(client?.nome) !== tx(client?.razao) && (
              <div style={{ fontSize: 10, color: MUTED, lineHeight: 1.3 }}>{tx(client?.nome)}</div>
            )}
            <div
              style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: '2px 18px',
                marginTop: 4,
                fontSize: 10,
                color: MUTED,
              }}
            >
              {doc(client?.cgcpf) !== '—' && (
                <span>
                  <strong style={{ color: INK }}>{docLabel}:</strong> {doc(client?.cgcpf)}
                </span>
              )}
              {tx(client?.inscricaoEstadual) && (
                <span>
                  <strong style={{ color: INK }}>IE:</strong> {tx(client?.inscricaoEstadual)}
                </span>
              )}
              {enderecoCli && <span>{enderecoCli}</span>}
              {phone(client?.telefone, client?.ddd) !== '—' && (
                <span>
                  <strong style={{ color: INK }}>Tel:</strong>{' '}
                  {phone(client?.telefone, client?.ddd)}
                </span>
              )}
              {tx(client?.email) && <span>{tx(client?.email)}</span>}
            </div>
          </div>
        </div>

        {/* ── Itens ───────────────────────────────────────────────────────── */}
        <div style={{ padding: '0 28px 0' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
            <thead>
              <tr style={{ background: '#F4F7FB' }}>
                {['Cód.', 'Produto', 'Qtd', 'Preço un.', 'Desc.', 'Total'].map((h, i) => (
                  <th
                    key={h}
                    style={{
                      textAlign: i >= 2 ? 'right' : 'left',
                      padding: '8px 8px',
                      color: MUTED,
                      fontWeight: 700,
                      fontSize: 9.5,
                      letterSpacing: '0.05em',
                      textTransform: 'uppercase',
                      borderBottom: `2px solid ${LINE}`,
                    }}
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {order.itens.map((it, idx) => (
                <tr key={it.id} style={{ background: idx % 2 ? '#FBFCFE' : '#fff' }}>
                  <td
                    style={{ padding: '7px 8px', color: MUTED, borderBottom: `1px solid ${LINE}` }}
                  >
                    {it.codProduto ?? '—'}
                  </td>
                  <td style={{ padding: '7px 8px', color: INK, borderBottom: `1px solid ${LINE}` }}>
                    {it.descProduto ?? '—'}
                  </td>
                  <td
                    style={{
                      padding: '7px 8px',
                      textAlign: 'right',
                      borderBottom: `1px solid ${LINE}`,
                    }}
                  >
                    {qty(it.qtd)}
                  </td>
                  <td
                    style={{
                      padding: '7px 8px',
                      textAlign: 'right',
                      borderBottom: `1px solid ${LINE}`,
                    }}
                  >
                    {money(it.precoUnitario)}
                  </td>
                  <td
                    style={{
                      padding: '7px 8px',
                      textAlign: 'right',
                      color: MUTED,
                      borderBottom: `1px solid ${LINE}`,
                    }}
                  >
                    {Number(it.descontoPerc) > 0 ? `${Number(it.descontoPerc)}%` : '—'}
                  </td>
                  <td
                    style={{
                      padding: '7px 8px',
                      textAlign: 'right',
                      fontWeight: 600,
                      color: INK,
                      borderBottom: `1px solid ${LINE}`,
                    }}
                  >
                    {money(it.total)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* ── Totais ──────────────────────────────────────────────────────── */}
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'flex-end',
            gap: 16,
            padding: '14px 28px 4px',
          }}
        >
          {/* Peso e cubagem do pedido (logística/frete) */}
          <div style={{ fontSize: 10.5, color: MUTED, lineHeight: 1.8 }}>
            {Number(order.pesoTotal ?? 0) > 0 && (
              <div>
                <strong style={{ color: INK }}>Peso total:</strong>{' '}
                {Number(order.pesoTotal).toLocaleString('pt-BR', { maximumFractionDigits: 2 })} kg
              </div>
            )}
            {Number(order.m3Total ?? 0) > 0 && (
              <div>
                <strong style={{ color: INK }}>Volume:</strong>{' '}
                {Number(order.m3Total).toLocaleString('pt-BR', { maximumFractionDigits: 3 })} m³
              </div>
            )}
          </div>
          <div style={{ width: 300 }}>
            <TotRow k="Total dos produtos" v={money(order.totalProdutos)} />
            {Number(order.totalIpi) > 0 && <TotRow k="IPI" v={money(order.totalIpi)} />}
            {Number(order.totalIcmsst) > 0 && <TotRow k="ICMS-ST" v={money(order.totalIcmsst)} />}
            {temDesc && (
              <TotRow
                k={`Desconto${Number(order.descontoPerc) > 0 ? ` (${Number(order.descontoPerc)}%)` : ''}`}
                v={`- ${money(order.descontoValor)}`}
              />
            )}
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginTop: 8,
                padding: '10px 14px',
                background: BLUE,
                borderRadius: 6,
                color: '#fff',
              }}
            >
              <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.04em' }}>TOTAL</span>
              <span style={{ fontSize: 17, fontWeight: 800 }}>{money(order.total)}</span>
            </div>
          </div>
        </div>

        {/* ── Endereço de entrega + Observações ───────────────────────────── */}
        {(order.endEntrega || order.obs) && (
          <div style={{ padding: '10px 28px 0', display: 'flex', gap: 24, flexWrap: 'wrap' }}>
            {order.endEntrega && (
              <div style={{ flex: 1, minWidth: 220 }}>
                <span style={label}>Endereço de entrega</span>
                <div style={{ fontSize: 11, color: '#475569', lineHeight: 1.5 }}>
                  {order.endEntrega}
                </div>
              </div>
            )}
            {order.obs && (
              <div style={{ flex: 1, minWidth: 220 }}>
                <span style={label}>Observações</span>
                <div style={{ fontSize: 11, color: '#475569', lineHeight: 1.5 }}>{order.obs}</div>
              </div>
            )}
          </div>
        )}
        <div
          style={{
            margin: '18px 28px 0',
            padding: '12px 0 18px',
            borderTop: `1px solid ${LINE}`,
            display: 'flex',
            justifyContent: 'space-between',
            fontSize: 9.5,
            color: '#94A3B8',
          }}
        >
          <span>
            Documento sem valor fiscal · Pedido de venda emitido pelo representante via SAR.
          </span>
          <span>SAR · Powered by JCS Sistemas</span>
        </div>
      </div>

      {/* CSS de impressão: esconde tudo menos o documento */}
      <style>{`
        @media print {
          @page { size: A4; margin: 10mm; }
          body * { visibility: hidden !important; }
          .sar-print, .sar-print * { visibility: visible !important; }
          .sar-print { position: absolute; left: 0; top: 0; width: 100% !important;
            max-width: none !important; box-shadow: none !important; border-radius: 0 !important; }
          .no-print { display: none !important; }
        }
      `}</style>
    </div>
  );
}

function TotRow({ k, v }: { k: string; v: string }) {
  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        padding: '4px 14px',
        fontSize: 11.5,
        color: MUTED,
      }}
    >
      <span>{k}</span>
      <span style={{ color: INK, fontWeight: 600 }}>{v}</span>
    </div>
  );
}
