"use client";

import { quantidadeDoItem } from "@/lib/orders/quantidade-do-item";
import { minimoDaLinhaGravada, ROTULO_DO_MINIMO } from "@/lib/adicionais";
import Image from "next/image";
import { formatDateBr } from "@/utils/formatters";
import type { CSSProperties } from "react";
import type { OrderItem, OrderStatus, Payment } from "@/types/orders";
import { normalizarCondicoes } from "@/lib/condicoes-comerciais";
import { CondicoesParaImpressao } from "@/components/quotes/condicoes-comerciais";

const statusLabel: Record<OrderStatus, string> = {
  pending_production: "Aguardando Produção",
  in_production: "Em Produção",
  finished: "Finalizado",
  delivered: "Entregue",
  canceled: "Cancelado",
};

function formatMoney(value: number) {
  return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value || 0);
}

function isPdvOrder(
  order: Pick<OrderPrintDocumentOrder, "quotes" | "internal_notes"> | null | undefined
) {
  if (!order) return false;
  const quoteTitle = String(order.quotes?.title || "").toLowerCase();
  const quoteInternalNotes = String(order.quotes?.internal_notes || "").toLowerCase();
  const orderInternalNotes = String(order.internal_notes || "").toLowerCase();
  return (
    quoteTitle.includes("venda pdv") ||
    quoteInternalNotes.includes("origem:pdv") ||
    orderInternalNotes.includes("pdv")
  );
}

export type OrderPrintDocumentOrder = {
  id: string;
  number: number | string;
  status: OrderStatus;
  created_at?: string | null;
  total_amount?: number | null;
  paid_amount?: number | null;
  delivery_date?: string | null;
  /* As condições combinadas na proposta (formato de lib/condicoes-comerciais). */
  payment_terms?: unknown;
  notes?: string | null;
  internal_notes?: string | null;
  approval_signature?: string | null;
  approval_signed_name?: string | null;
  approval_signed_at?: string | null;
  quotes?: {
    id?: string | null;
    number?: number | null;
    user_id?: string | null;
    share_token?: string | null;
    share_enabled?: boolean | null;
    title?: string | null;
    internal_notes?: string | null;
    notes?: string | null;
    subtotal?: number | null;
    discount?: number | null;
    shipping?: number | null;
    total?: number | null;
    delivery_date?: string | null;
  } | null;
  clients?: {
    name?: string | null;
    company_name?: string | null;
    type?: "pf" | "pj" | null;
    is_deleted?: boolean | null;
    document?: string | null;
    email?: string | null;
    phone?: string | null;
    whatsapp?: string | null;
    whatsapp_notify?: boolean | null;
    address_street?: string | null;
    address_number?: string | null;
    address_complement?: string | null;
    address_neighborhood?: string | null;
    address_city?: string | null;
    address_state?: string | null;
    address_zip?: string | null;
    notes?: string | null;
    tags?: string[] | null;
    active?: boolean | null;
  } | null;
};

export type OrderPrintCompanyProfile = {
  slug?: string | null;
  store_name?: string | null;
  logo_url?: string | null;
  catalog_logo_url?: string | null;
  catalog_name?: string | null;
  cnpj?: string | null;
  address?: string | null;
  company_phone?: string | null;
  phone?: string | null;
  company_whatsapp?: string | null;
  whatsapp?: string | null;
  company_email?: string | null;
  quote_signature_required?: boolean | null;
  quote_art_registration_enabled?: boolean | null;
  quote_art_approval_required?: boolean | null;
  quote_default_notes_enabled?: boolean | null;
  quote_default_notes?: string | null;
};

type OrderPrintDocumentProps = {
  order: OrderPrintDocumentOrder;
  items: OrderItem[];
  payments: Payment[];
  profile: OrderPrintCompanyProfile | null;
  creatorName?: string | null;
  className?: string;
  style?: CSSProperties;
  alwaysVisible?: boolean;
};

export function OrderPrintDocument({
  order,
  items,
  payments,
  profile,
  creatorName,
  className = "",
  style,
  alwaysVisible = false,
}: OrderPrintDocumentProps) {
  const totalPaid = payments.reduce((acc, payment) => acc + (payment.amount || 0), 0);
  const remainingAmount = (order?.total_amount || 0) - totalPaid;
  const condicoes = normalizarCondicoes(order?.payment_terms);
  const itemsSubtotal = items.reduce((acc, item) => acc + Number(item.total_price || item.quantity * item.unit_price || 0), 0);
  const hasQuoteBreakdown =
    order.quotes?.subtotal != null ||
    order.quotes?.discount != null ||
    order.quotes?.shipping != null ||
    order.quotes?.total != null;
  const pdvOrder = isPdvOrder(order);
  const quoteSubtotal = hasQuoteBreakdown ? Number(order.quotes?.subtotal ?? itemsSubtotal) : itemsSubtotal;
  const quoteDiscount = hasQuoteBreakdown
    ? Math.max(0, Number(order.quotes?.discount ?? 0))
    : Math.max(0, quoteSubtotal - Number(order.total_amount || 0));
  const quoteShipping = hasQuoteBreakdown ? Math.max(0, Number(order.quotes?.shipping ?? 0)) : 0;
  const quoteTotal = hasQuoteBreakdown
    ? Number(order.quotes?.total ?? Math.max(0, quoteSubtotal - quoteDiscount + quoteShipping))
    : Math.max(0, Number(order.total_amount || 0));
  const dueLabel = order.quotes?.delivery_date ? formatDateBr(order.quotes.delivery_date) : "Não informada";

  return (
    <div
      className={`print-only print-order-root w-full bg-white text-black ${className}`.trim()}
      style={alwaysVisible ? { display: "block", ...style } : style}
    >
      <div className="mx-auto print-order-page px-2 py-4">
        <div className="flex items-start justify-between pb-6 border-b-2 border-zinc-900">
          <div className="flex items-center gap-4">
            {(profile?.logo_url || profile?.catalog_logo_url) && (
              <Image
                src={profile.logo_url || profile.catalog_logo_url || ""}
                alt="Logo"
                width={160}
                height={50}
                sizes="160px"
                className="h-12 w-auto object-contain"
                unoptimized
              />
            )}
            <div>
              <h1 className="text-xl font-bold text-zinc-900 tracking-tight">
                {profile?.catalog_name || profile?.store_name || "Empresa"}
              </h1>
              <div className="mt-1 text-[10px] text-zinc-600 space-y-0.5">
                {profile?.cnpj && <div>CNPJ: {profile.cnpj}</div>}
                {profile?.address && <div>{profile.address}</div>}
                {(profile?.company_phone || profile?.phone || profile?.company_whatsapp || profile?.whatsapp) && (
                  <div>
                    {[
                      profile?.company_phone || profile?.phone ? `Tel: ${profile?.company_phone || profile?.phone}` : null,
                      profile?.company_whatsapp || profile?.whatsapp
                        ? `WhatsApp: ${profile?.company_whatsapp || profile?.whatsapp}`
                        : null,
                    ]
                      .filter(Boolean)
                      .join(" • ")}
                  </div>
                )}
              </div>
            </div>
          </div>
          <div className="text-right">
            <div className="text-[10px] font-bold uppercase tracking-[0.2em] text-zinc-400">Pedido</div>
            <div className="mt-1 text-3xl font-black tracking-tighter text-zinc-900">#{order.number}</div>
            <div className="mt-2 text-[10px] font-medium text-zinc-500">
              {order.created_at ? `Emitido em ${new Date(order.created_at).toLocaleDateString("pt-BR")}` : ""}
            </div>
            {creatorName && <div className="text-[10px] font-medium text-zinc-500">Resp: {creatorName}</div>}
          </div>
        </div>

        <div className="mt-6 grid grid-cols-4 gap-4">
          <div>
            <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">
              {pdvOrder ? "Status da venda" : "Status do pedido"}
            </div>
            <div className="text-xs font-bold text-zinc-900">
              {pdvOrder
                ? order.status === "canceled"
                  ? "Venda cancelada no PDV"
                  : "Venda concluída no PDV"
                : statusLabel[order.status]}
            </div>
          </div>
          {order.quotes && !pdvOrder && (
            <div>
              <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">Orçamento</div>
              <div className="text-xs font-bold text-zinc-900">#{order.quotes.number}</div>
            </div>
          )}
          {pdvOrder && (
            <div>
              <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">Origem</div>
              <div className="text-xs font-bold text-zinc-900">Venda direta no PDV</div>
            </div>
          )}
          <div>
            <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">Entrega Prevista</div>
            <div className="text-xs font-bold text-zinc-900">{dueLabel}</div>
          </div>
          <div>
            <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">Total</div>
            <div className="text-xs font-black text-zinc-900">{formatMoney(order.total_amount || 0)}</div>
          </div>
        </div>

        <div className="mt-6 border border-zinc-200 p-3">
          <div className="mb-1 text-[9px] font-bold uppercase tracking-wider text-zinc-400">Cliente</div>
          <div className="text-sm font-bold text-zinc-900">
            {order.clients?.company_name ? `${order.clients.company_name} — ${order.clients.name}` : order.clients?.name || "Cliente"}
          </div>
          <div className="mt-1 flex flex-wrap gap-x-6 gap-y-1 text-[11px] font-medium text-zinc-600">
            {order.clients?.document && (
              <div>
                {order.clients.document.replace(/\D/g, "").length === 14 ? "CNPJ: " : "CPF: "}
                {order.clients.document}
              </div>
            )}
            {order.clients?.whatsapp && <div>WhatsApp: {order.clients.whatsapp}</div>}
            {order.clients?.email && <div>E-mail: {order.clients.email}</div>}
          </div>
          {order.clients?.is_deleted ? (
            <span className="mt-2 inline-flex rounded-sm bg-red-100 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-red-700">
              Cliente Excluído
            </span>
          ) : null}
        </div>

        <div className="mt-8">
          <table className="w-full text-xs">
            <thead>
              <tr className="border-b-2 border-zinc-900">
                <th className="w-[45%] px-2 py-2 text-left text-[9px] font-bold uppercase tracking-wider text-zinc-900">Item / Descrição</th>
                <th className="w-[15%] px-2 py-2 text-center text-[9px] font-bold uppercase tracking-wider text-zinc-900">Tamanho</th>
                <th className="w-[10%] px-2 py-2 text-center text-[9px] font-bold uppercase tracking-wider text-zinc-900">Qtd</th>
                <th className="w-[15%] px-2 py-2 text-right text-[9px] font-bold uppercase tracking-wider text-zinc-900">Unitário</th>
                <th className="w-[15%] px-2 py-2 text-right text-[9px] font-bold uppercase tracking-wider text-zinc-900">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-200">
              {items.map((item, idx) => {
                /* Peças numa coluna; medida e área na outra. */
                const medidaDoItem = quantidadeDoItem(item);
                const minimoDoItem = minimoDaLinhaGravada(item);

                return (
                  <tr key={item.id} className="group">
                    <td className="px-2 py-3 align-top">
                      <div className="text-xs font-bold text-zinc-900">
                        {idx + 1}. {item.title}
                      </div>
                      {item.products?.sku || item.products?.barcode ? (
                        <div className="mt-1 text-[9px] font-medium uppercase tracking-wider text-zinc-500">
                          {item.products.sku ? `SKU: ${item.products.sku}` : ""}
                          {item.products.sku && item.products.barcode ? " • " : ""}
                          {item.products.barcode ? `Cód: ${item.products.barcode}` : ""}
                        </div>
                      ) : null}
                      {item.description && (
                        <div className="mt-1 max-w-md text-[11px] leading-relaxed text-zinc-600">{item.description}</div>
                      )}
                      {minimoDoItem ? (
                        <div className="mt-1">
                          <span className="inline-block rounded-sm border border-zinc-900 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-zinc-900">
                            {ROTULO_DO_MINIMO}
                          </span>
                        </div>
                      ) : null}
                    </td>
                    <td className="px-2 pt-3 pb-3 text-center align-top text-[11px] font-medium text-zinc-600">
                      {medidaDoItem.medida ?? "-"}
                      {medidaDoItem.total ? <div className="font-bold text-zinc-900">{medidaDoItem.total}</div> : null}
                    </td>
                    <td className="px-2 pt-3 pb-3 text-center align-top text-xs font-bold text-zinc-900">{medidaDoItem.pecasTexto}</td>
                    <td className="px-2 pt-3 pb-3 text-right align-top text-[11px] font-medium text-zinc-600">
                      {minimoDoItem ? "Valor mínimo" : formatMoney(item.unit_price || 0)}
                    </td>
                    <td className="px-2 pt-3 pb-3 text-right align-top text-xs font-black text-zinc-900">
                      {formatMoney(item.total_price || 0)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="mt-4 flex justify-end">
          <div className="w-56">
            <div className="flex items-center justify-between border-b border-zinc-200 py-1.5">
              <span className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Subtotal</span>
              <span className="text-xs font-bold text-zinc-900">{formatMoney(quoteSubtotal)}</span>
            </div>
            {quoteDiscount > 0 && (
              <div className="flex items-center justify-between border-b border-zinc-200 py-1.5">
                <span className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Desconto</span>
                <span className="text-xs font-bold text-red-600">- {formatMoney(quoteDiscount)}</span>
              </div>
            )}
            {quoteShipping > 0 && (
              <div className="flex items-center justify-between border-b border-zinc-200 py-1.5">
                <span className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Frete</span>
                <span className="text-xs font-bold text-zinc-900">+ {formatMoney(quoteShipping)}</span>
              </div>
            )}
            <div className="flex items-center justify-between border-b-2 border-zinc-900 py-2">
              <span className="text-[11px] font-black uppercase tracking-wider text-zinc-900">Total do Pedido</span>
              <span className="text-lg font-black tracking-tight text-zinc-900">{formatMoney(quoteTotal)}</span>
            </div>
            {payments.length > 0 && (
              <>
                <div className="mt-1 flex items-center justify-between py-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Total Pago</span>
                  <span className="text-xs font-bold text-emerald-600">{formatMoney(totalPaid)}</span>
                </div>
                <div className="flex items-center justify-between py-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Restante</span>
                  <span className={`text-xs font-bold ${remainingAmount > 0 ? "text-red-600" : "text-zinc-900"}`}>
                    {formatMoney(remainingAmount)}
                  </span>
                </div>
              </>
            )}
          </div>
        </div>

        {condicoes && (
          <div className="mt-10 print-avoid-break">
            <div className="mb-3 border-b border-zinc-200 pb-2 text-[10px] font-bold uppercase tracking-wider text-zinc-400">
              Condições de Pagamento
            </div>
            <CondicoesParaImpressao
              condicoes={condicoes}
              total={quoteTotal}
              datas={{ aprovacao: order.created_at, entrega: order.delivery_date ?? order.quotes?.delivery_date ?? null }}
              moldura={false}
            />
          </div>
        )}

        {payments.length > 0 && (
          <div className="mt-12 print-avoid-break">
            <div className="mb-3 border-b border-zinc-200 pb-2 text-[10px] font-bold uppercase tracking-wider text-zinc-400">
              Histórico de Pagamentos
            </div>
            <table className="w-full text-xs">
              <tbody className="divide-y divide-zinc-100">
                {payments.map((payment) => (
                  <tr key={payment.id}>
                    <td className="w-32 py-2 font-medium text-zinc-500">
                      {new Date(payment.payment_date).toLocaleDateString("pt-BR")}
                    </td>
                    <td className="py-2 font-semibold text-zinc-900">
                      {payment.payment_method === "credit_card"
                        ? "Cartão de Crédito"
                        : payment.payment_method === "debit_card"
                          ? "Cartão de Débito"
                          : payment.payment_method === "pix"
                            ? "Pix"
                            : payment.payment_method === "cash"
                              ? "Dinheiro"
                              : payment.payment_method === "transfer"
                                ? "Transferência"
                                : payment.payment_method}
                    </td>
                    <td className="py-2 text-right font-bold text-zinc-900">{formatMoney(payment.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div className="mt-12 grid grid-cols-2 gap-8 print-avoid-break">
          <div>
            {order.approval_signature ? (
              <div>
                <div className="mb-3 border-b border-zinc-200 pb-2 text-[10px] font-bold uppercase tracking-wider text-zinc-400">
                  Assinatura do Cliente
                </div>
                <div className="mt-4 rounded-xl border border-zinc-100 bg-zinc-50/50 p-4">
                  <Image
                    src={order.approval_signature}
                    alt="Assinatura do cliente"
                    width={400}
                    height={80}
                    sizes="100vw"
                    className="h-16 w-full object-contain mix-blend-multiply"
                    unoptimized
                  />
                </div>
                <div className="mt-3 text-center text-xs font-bold text-zinc-900">
                  {order.approval_signed_name || "Assinado Digitalmente"}
                </div>
                {order.approval_signed_at && (
                  <div className="mt-0.5 text-center text-[10px] font-medium text-zinc-500">
                    {new Date(order.approval_signed_at).toLocaleString("pt-BR")}
                  </div>
                )}
              </div>
            ) : (
              <div className="pt-8">
                <div className="w-full border-t border-zinc-400 pt-2 text-center text-xs font-bold text-zinc-900">
                  Assinatura do Cliente
                </div>
                <div className="mt-1 text-center text-[10px] font-medium text-zinc-500">
                  {order.clients?.company_name ? `${order.clients.company_name} — ${order.clients.name}` : order.clients?.name || "Cliente"}
                </div>
              </div>
            )}
          </div>

          <div>
            {((profile?.quote_default_notes_enabled && profile?.quote_default_notes) || order.quotes?.notes || order.notes) && (
              <div>
                <div className="mb-3 border-b border-zinc-200 pb-2 text-[10px] font-bold uppercase tracking-wider text-zinc-400">
                  Observações
                </div>
                <div className="space-y-4 text-xs font-medium leading-relaxed text-zinc-600">
                  {profile?.quote_default_notes_enabled && profile?.quote_default_notes && (
                    <div className="whitespace-pre-wrap">{profile.quote_default_notes}</div>
                  )}
                  {order.quotes?.notes && <div className="whitespace-pre-wrap">{order.quotes.notes}</div>}
                  {order.notes && <div className="whitespace-pre-wrap">{order.notes}</div>}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
