"use client";

import { useMemo, useState } from "react";
import { CalendarClock, Eye, FileText, Loader2, Pencil, Plus, Trash2, Wallet } from "lucide-react";
import { Order, Payment } from "@/types/orders";
import { formatMoney } from "@/lib/utils";
import { PaymentModal } from "./payment-modal";
import { IconeDaForma } from "@/components/quotes/condicoes-comerciais";
import {
  cronograma,
  descreverCondicoes,
  formatarDia,
  nomeDaForma,
  normalizarCondicoes,
  proximaParcelaEmAberto,
  situacaoDasParcelas,
  type ParcelaComSituacao,
  type SituacaoDaParcela,
} from "@/lib/condicoes-comerciais";
import { deletePayment, updatePaymentNotes } from "@/app/actions/financial";
import { PixIcon, CashIcon, CreditCardIcon, DebitCardIcon, TransferIcon } from "@/components/icons/payment-icons";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";

type CompanyReceiptProfile = {
  store_name?: string | null;
  catalog_name?: string | null;
  logo_url?: string | null;
  catalog_logo_url?: 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;
};

type OrderWithClientDetails = Order & {
  clients?: {
    name?: string | null;
    company_name?: string | null;
    document?: string | 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;
  } | null;
};

interface FinancialSectionProps {
  order: OrderWithClientDetails;
  payments: Payment[];
  onUpdate: () => void;
  canWrite: boolean;
  profile?: CompanyReceiptProfile | null;
}

type PaymentWithReversalMeta = Payment & {
  reversed_at?: string | null;
  reversal_reason?: string | null;
};

const methodLabels: Record<string, string> = {
  pix: "Pix",
  cash: "Dinheiro",
  credit_card: "Cartao de Credito",
  debit_card: "Cartao de Debito",
  transfer: "Transferencia",
};

const methodIcons: Record<string, React.ReactNode> = {
  pix: <PixIcon className="w-10 h-10 text-[#4DB6AC]" />,
  cash: <CashIcon className="w-10 h-10 text-green-600" />,
  credit_card: <CreditCardIcon className="w-10 h-10 text-indigo-600" />,
  debit_card: <DebitCardIcon className="w-10 h-10 text-indigo-400" />,
  transfer: <TransferIcon className="w-10 h-10 text-purple-600" />,
};

/* As parcelas do combinado na proposta. */
const ROTULO_DA_SITUACAO: Record<SituacaoDaParcela, string> = {
  paga: "Paga",
  parcial: "Parcial",
  pendente: "Em aberto",
  vencida: "Vencida",
};

const ESTILO_DA_SITUACAO: Record<SituacaoDaParcela, string> = {
  paga: "border-emerald-200 bg-emerald-50 text-emerald-700",
  parcial: "border-blue-200 bg-blue-50 text-blue-700",
  pendente: "border-zinc-200 bg-zinc-50 text-zinc-600",
  vencida: "border-red-200 bg-red-50 text-red-600",
};

const BOLINHA_DA_SITUACAO: Record<SituacaoDaParcela, string> = {
  paga: "bg-emerald-500",
  parcial: "bg-blue-500",
  pendente: "bg-zinc-300",
  vencida: "bg-red-500",
};

/* A forma combinada vira a forma do registro. Boleto e link não existem no
   livro de pagamentos: o dinheiro do boleto entra como transferência e o do
   link como cartão de crédito. */
function formaDoRegistro(forma: string | undefined) {
  if (!forma) return "";
  if (forma === "boleto") return "transfer";
  if (forma === "link") return "credit_card";
  return forma;
}

const financialStatusLabels: Record<string, string> = {
  unpaid: "Nao Pago",
  partially_paid: "Parcialmente Pago",
  paid: "Pago",
};

const financialStatusStyles: Record<string, string> = {
  unpaid: "bg-zinc-100 text-zinc-600 border-zinc-200",
  partially_paid: "bg-blue-50 text-blue-700 border-blue-200",
  paid: "bg-emerald-50 text-emerald-700 border-emerald-200",
};

function toNumber(value: number | null | undefined) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
}

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

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

function combineAddress(parts: Array<string | null | undefined>) {
  return parts
    .map((part) => (part || "").trim())
    .filter(Boolean)
    .join(", ");
}

function parseDateToTime(value: string | null | undefined) {
  if (!value) return 0;
  const date = new Date(value);
  const time = date.getTime();
  return Number.isFinite(time) ? time : 0;
}

export function FinancialSection({ order, payments, onUpdate, canWrite, profile }: FinancialSectionProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [issuingReceiptId, setIssuingReceiptId] = useState<string | null>(null);
  const [noteModalPayment, setNoteModalPayment] = useState<Payment | null>(null);
  const [isEditingNote, setIsEditingNote] = useState(false);
  const [noteDraft, setNoteDraft] = useState("");
  const [savingNote, setSavingNote] = useState(false);
  const [prefill, setPrefill] = useState<{ amount?: number; method?: string; notes?: string } | null>(null);

  const activePayments = useMemo(
    () => payments.filter((payment) => !(payment as PaymentWithReversalMeta).reversed_at),
    [payments]
  );

  const paidAmount = activePayments.reduce((acc, p) => acc + Number(p.amount), 0);

  const total = Number(order.total_amount);
  const paid = order.paid_amount !== undefined ? Number(order.paid_amount) : paidAmount;
  const pending = Math.max(0, total - paid);

  let currentStatus = order.financial_status || "unpaid";
  const isFullyPaid = paid >= total - 0.01;

  if (isFullyPaid) {
    currentStatus = "paid";
  } else if (!order.financial_status) {
    if (paid > 0) currentStatus = "partially_paid";
  }

  /* O combinado na proposta, copiado do orçamento na aprovação. O dinheiro
     registrado quita as parcelas na ordem; a aprovação é a data do pedido. */
  const condicoes = useMemo(() => normalizarCondicoes(order.payment_terms), [order.payment_terms]);
  const condicoesEscritas = useMemo(
    () => (condicoes ? descreverCondicoes(condicoes, total) : null),
    [condicoes, total]
  );
  const parcelas = useMemo<ParcelaComSituacao[]>(() => {
    if (!condicoes) return [];
    return situacaoDasParcelas(
      cronograma(condicoes, total, { aprovacao: order.created_at, entrega: order.delivery_date ?? null }),
      paid
    );
  }, [condicoes, total, paid, order.created_at, order.delivery_date]);
  const proximaParcela = useMemo(() => proximaParcelaEmAberto(parcelas), [parcelas]);

  function registrarParcela(parcela: ParcelaComSituacao, falta: number) {
    setPrefill({
      amount: Math.min(falta, pending),
      method: formaDoRegistro(condicoes?.formas[0]),
      notes: `${parcela.rotulo} — combinado na proposta`,
    });
    setIsModalOpen(true);
  }

  const paymentTotalsById = useMemo(() => {
    const map = new Map<string, { before: number; after: number; sequence: number }>();
    const sortedAsc = [...activePayments].sort((a, b) => {
      const byDate = parseDateToTime(a.payment_date) - parseDateToTime(b.payment_date);
      if (byDate !== 0) return byDate;
      const byCreated = parseDateToTime(a.created_at) - parseDateToTime(b.created_at);
      if (byCreated !== 0) return byCreated;
      return a.id.localeCompare(b.id);
    });

    let running = 0;
    sortedAsc.forEach((payment, index) => {
      const before = running;
      running += toNumber(payment.amount);
      map.set(payment.id, {
        before,
        after: running,
        sequence: index + 1,
      });
    });

    return map;
  }, [activePayments]);

  const sortedPayments = useMemo(() => {
    return [...activePayments].sort((a, b) => {
      const byDate = parseDateToTime(a.payment_date) - parseDateToTime(b.payment_date);
      if (byDate !== 0) return byDate;
      const byCreated = parseDateToTime(a.created_at) - parseDateToTime(b.created_at);
      if (byCreated !== 0) return byCreated;
      return a.id.localeCompare(b.id);
    });
  }, [activePayments]);

  const openPaymentNoteModal = (payment: Payment) => {
    setNoteModalPayment(payment);
    setNoteDraft(payment.notes || "");
    setIsEditingNote(false);
  };

  const closePaymentNoteModal = () => {
    if (savingNote) return;
    setNoteModalPayment(null);
    setNoteDraft("");
    setIsEditingNote(false);
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Tem certeza que deseja excluir este pagamento?")) return;

    setDeletingId(id);
    try {
      const result = await deletePayment(id, order.id);
      if (result?.error) {
        alert(result.error);
        return;
      }
      onUpdate();
    } finally {
      setDeletingId(null);
    }
  };

  const printReceipt = async (receiptPayload: {
    company: {
      name: string;
      document: string | null;
      address: string | null;
      phone: string | null;
      email: string | null;
      logoUrl: string | null;
    };
    client: {
      name: string | null;
      companyName: string | null;
      document: string | null;
      address: string | null;
    };
    order: {
      number: number;
      totalAmount: number;
    };
    payment: {
      id: string;
      amount: number;
      paymentDate: string;
      method: string;
      notes: string | null;
    };
    receipt: {
      issuedAt: string;
      sequence: number;
      paidBefore: number;
      paidAfter: number;
      label?: string | null;
    };
  }) => {
    let previousDocumentTitle: string | null = null;
    try {
      const { buildPaymentReceiptHtml, buildPaymentReceiptFilename } = await import("@/lib/orders/payment-receipt-print");
      const html = buildPaymentReceiptHtml(receiptPayload, { autoPrint: false, autoClose: false });
      const suggestedFileTitle = buildPaymentReceiptFilename(receiptPayload).replace(/\.pdf$/i, "");

      const iframe = document.createElement("iframe");
      iframe.setAttribute("aria-hidden", "true");
      iframe.style.position = "fixed";
      iframe.style.right = "0";
      iframe.style.bottom = "0";
      iframe.style.width = "0";
      iframe.style.height = "0";
      iframe.style.border = "0";
      iframe.style.opacity = "0";
      iframe.style.pointerEvents = "none";

      previousDocumentTitle = document.title;
      document.title = suggestedFileTitle;

      const cleanup = () => {
        iframe.onload = null;
        if (iframe.parentNode) {
          iframe.parentNode.removeChild(iframe);
        }
        if (previousDocumentTitle !== null) {
          document.title = previousDocumentTitle;
          previousDocumentTitle = null;
        }
      };

      iframe.onload = () => {
        const frameWindow = iframe.contentWindow;
        if (!frameWindow) {
          cleanup();
          alert("Nao foi possivel abrir a impressao do recibo.");
          return;
        }

        try {
          frameWindow.document.title = suggestedFileTitle;
        } catch {
          // noop
        }

        const runPrint = () => {
          frameWindow.focus();
          frameWindow.print();
        };

        const fontFaceSet = frameWindow.document.fonts;
        if (fontFaceSet?.ready) {
          fontFaceSet.ready
            .then(() => window.setTimeout(runPrint, 120))
            .catch(() => window.setTimeout(runPrint, 220));
        } else {
          window.setTimeout(runPrint, 220);
        }

        window.setTimeout(cleanup, 300000);
      };

      iframe.srcdoc = html;
      document.body.appendChild(iframe);
    } catch (error) {
      console.error("Erro ao emitir recibo:", error);
      alert("Nao foi possivel emitir o recibo agora.");
      if (previousDocumentTitle !== null) {
        document.title = previousDocumentTitle;
      }
    } finally {
    }
  };

  const handleIssueReceipt = async (payment: Payment) => {
    setIssuingReceiptId(payment.id);
    try {
      const paymentTotals = paymentTotalsById.get(payment.id) || {
        before: Math.max(0, paid - toNumber(payment.amount)),
        after: paid,
        sequence: 1,
      };

      const clientAddress = combineAddress([
        order.clients?.address_street,
        order.clients?.address_number,
        order.clients?.address_complement,
        order.clients?.address_neighborhood,
        combineAddress([order.clients?.address_city, order.clients?.address_state]),
        order.clients?.address_zip ? `CEP ${order.clients.address_zip}` : "",
      ]);

      const companyName = (profile?.store_name || profile?.catalog_name || "Empresa").trim();
      const companyContact =
        profile?.company_phone ||
        profile?.company_whatsapp ||
        profile?.phone ||
        profile?.whatsapp ||
        null;

      await printReceipt({
        company: {
          name: companyName,
          document: profile?.cnpj || null,
          address: profile?.address || null,
          phone: companyContact,
          email: profile?.company_email || null,
          logoUrl: profile?.logo_url || profile?.catalog_logo_url || null,
        },
        client: {
          name: order.clients?.name || null,
          companyName: order.clients?.company_name || null,
          document: formatDocument(order.clients?.document) || null,
          address: clientAddress || null,
        },
        order: {
          number: order.number,
          totalAmount: toNumber(order.total_amount),
        },
        payment: {
          id: payment.id,
          amount: toNumber(payment.amount),
          paymentDate: payment.payment_date,
          method: payment.payment_method,
          notes: payment.notes || null,
        },
        receipt: {
          issuedAt: new Date().toISOString(),
          sequence: paymentTotals.sequence,
          paidBefore: paymentTotals.before,
          paidAfter: paymentTotals.after,
        },
      });
    } finally {
      setIssuingReceiptId(null);
    }
  };

  const handleIssueTotalReceipt = async () => {
    if (!isFullyPaid || sortedPayments.length === 0) return;

    setIssuingReceiptId("__total__");
    try {
      const latestPayment = sortedPayments[sortedPayments.length - 1];
      const clientAddress = combineAddress([
        order.clients?.address_street,
        order.clients?.address_number,
        order.clients?.address_complement,
        order.clients?.address_neighborhood,
        combineAddress([order.clients?.address_city, order.clients?.address_state]),
        order.clients?.address_zip ? `CEP ${order.clients.address_zip}` : "",
      ]);

      const companyName = (profile?.store_name || profile?.catalog_name || "Empresa").trim();
      const companyContact =
        profile?.company_phone ||
        profile?.company_whatsapp ||
        profile?.phone ||
        profile?.whatsapp ||
        null;

      const uniqueMethodLabels = Array.from(
        new Set(sortedPayments.map((payment) => methodLabels[payment.payment_method] || payment.payment_method).filter(Boolean))
      );

      const totalReceiptNote =
        sortedPayments.length > 1
          ? `Recibo consolidado de quitacao total referente a ${sortedPayments.length} pagamentos registrados.`
          : "Recibo consolidado de quitacao total do pedido.";

      await printReceipt({
        company: {
          name: companyName,
          document: profile?.cnpj || null,
          address: profile?.address || null,
          phone: companyContact,
          email: profile?.company_email || null,
          logoUrl: profile?.logo_url || profile?.catalog_logo_url || null,
        },
        client: {
          name: order.clients?.name || null,
          companyName: order.clients?.company_name || null,
          document: formatDocument(order.clients?.document) || null,
          address: clientAddress || null,
        },
        order: {
          number: order.number,
          totalAmount: toNumber(order.total_amount),
        },
        payment: {
          id: `total-${order.id}`,
          amount: toNumber(order.total_amount),
          paymentDate: latestPayment.payment_date,
          method: uniqueMethodLabels.join(" + "),
          notes: totalReceiptNote,
        },
        receipt: {
          issuedAt: new Date().toISOString(),
          sequence: sortedPayments.length,
          paidBefore: 0,
          paidAfter: toNumber(order.total_amount),
          label: "Quitacao total",
        },
      });
    } finally {
      setIssuingReceiptId(null);
    }
  };

  const handleSavePaymentNote = async () => {
    if (!noteModalPayment) return;
    setSavingNote(true);
    try {
      const result = await updatePaymentNotes(noteModalPayment.id, order.id, noteDraft);
      if (result?.error) {
        alert(result.error);
        return;
      }
      onUpdate();
      setNoteModalPayment({
        ...noteModalPayment,
        notes: noteDraft.trim() || undefined,
      });
      setIsEditingNote(false);
    } finally {
      setSavingNote(false);
    }
  };

  return (
    <div className="mt-8 flex flex-col gap-6 border-t border-zinc-200/60 pt-8">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className="rounded-lg bg-[var(--ks-color-bg-soft)] p-2.5 text-[var(--ks-color-primary)]">
            <Wallet className="w-5 h-5" />
          </div>
          <div>
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-bold text-[var(--ks-color-brand-dark)]">Financeiro</h2>
              <span className={`text-xs px-2.5 py-0.5 rounded-full border font-medium uppercase tracking-wide ${financialStatusStyles[currentStatus] || financialStatusStyles.unpaid}`}>
                {financialStatusLabels[currentStatus] || financialStatusLabels.unpaid}
              </span>
            </div>
            <p className="text-sm text-zinc-500">Pagamentos e saldo</p>
          </div>
        </div>

        {pending > 0.01 && canWrite && (
          <button
            onClick={() => {
              setPrefill(null);
              setIsModalOpen(true);
            }}
            className="ks-button ks-button-primary"
          >
            <Plus className="w-4 h-4" />
            Registrar Pagamento
          </button>
        )}
      </div>

      <div className="grid grid-cols-3 gap-2 md:gap-4">
        <div className="flex flex-col gap-1 rounded-xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-soft)] p-3 md:p-5">
          <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-wide md:text-xs md:tracking-widest">Valor Total</span>
          <span className="text-base font-bold text-zinc-900 md:text-2xl">{formatMoney(total)}</span>
        </div>
        <div className="flex flex-col gap-1 rounded-xl border border-emerald-200 bg-emerald-50/40 p-3 md:p-5">
          <span className="text-[10px] font-bold text-emerald-600 uppercase tracking-wide relative md:text-xs md:tracking-widest">Valor Pago</span>
          <span className="text-base font-bold text-emerald-700 relative md:text-2xl">{formatMoney(paid)}</span>
        </div>
        <div className="flex flex-col gap-1 rounded-xl border border-indigo-200 bg-indigo-50/40 p-3 md:p-5">
          <span className="text-[10px] font-bold text-indigo-600 uppercase tracking-wide relative md:text-xs md:tracking-widest">Saldo Pendente</span>
          <span className="text-base font-bold text-indigo-700 relative md:text-2xl">{formatMoney(pending)}</span>
        </div>
      </div>

      {condicoes && (
        <div className="overflow-hidden rounded-xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)]">
          <div className="flex flex-wrap items-start justify-between gap-3 border-b border-zinc-100 bg-zinc-50/70 px-5 py-4">
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                <CalendarClock className="h-4 w-4 text-[var(--ks-color-primary)]" />
                <h3 className="text-sm font-bold text-zinc-900">Combinado na proposta</h3>
              </div>
              <p className="mt-1 text-sm text-zinc-700">{condicoesEscritas?.pagamento}</p>
              {condicoesEscritas?.observacoes && (
                <p className="mt-1 whitespace-pre-wrap text-xs text-zinc-500">{condicoesEscritas.observacoes}</p>
              )}
            </div>
            <div className="flex flex-wrap items-center gap-1.5">
              {condicoes.formas.map((forma) => (
                <span
                  key={forma}
                  className="inline-flex items-center gap-1.5 rounded-full border border-zinc-200 bg-white px-2.5 py-1 text-xs font-medium text-zinc-700"
                >
                  <IconeDaForma codigo={forma} tamanho={14} />
                  {nomeDaForma(forma)}
                  {forma === "credit_card" && condicoes.cartao.parcelas > 1
                    ? ` até ${condicoes.cartao.parcelas}x${condicoes.cartao.sem_juros ? " sem juros" : ""}`
                    : ""}
                </span>
              ))}
            </div>
          </div>
          <ul className="divide-y divide-zinc-100">
            {parcelas.map((parcela) => {
              const falta = Math.max(0, Math.round((parcela.valor - parcela.pago) * 100) / 100);
              return (
                <li key={parcela.numero} className="flex flex-wrap items-center gap-x-4 gap-y-2 px-5 py-3">
                  <span className={`h-2.5 w-2.5 shrink-0 rounded-full ${BOLINHA_DA_SITUACAO[parcela.situacao]}`} />
                  <div className="min-w-[160px] flex-1">
                    <div className="text-sm font-semibold text-zinc-900">{parcela.rotulo}</div>
                    <div className="text-xs text-zinc-500">
                      {parcela.quando}
                      {parcela.vencimento ? ` · ${formatarDia(parcela.vencimento)}` : ""}
                    </div>
                  </div>
                  <span
                    className={`rounded-full border px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide ${ESTILO_DA_SITUACAO[parcela.situacao]}`}
                  >
                    {ROTULO_DA_SITUACAO[parcela.situacao]}
                  </span>
                  <div className="w-32 text-right">
                    <div className="text-sm font-bold text-zinc-900">{formatMoney(parcela.valor)}</div>
                    {parcela.situacao === "parcial" && (
                      <div className="text-[11px] text-zinc-500">pago {formatMoney(parcela.pago)}</div>
                    )}
                  </div>
                  {canWrite && parcela.situacao !== "paga" && pending > 0.01 ? (
                    <button
                      type="button"
                      onClick={() => registrarParcela(parcela, falta)}
                      className="inline-flex h-8 items-center justify-center rounded-full border border-[var(--ks-color-border-subtle)] bg-white px-3 text-xs font-semibold text-[var(--ks-color-primary)] transition-colors hover:bg-[var(--ks-color-primary-soft)]"
                    >
                      Registrar
                    </button>
                  ) : (
                    <span className="w-[86px]" />
                  )}
                </li>
              );
            })}
          </ul>
          {proximaParcela && pending > 0.01 && (
            <div className="border-t border-zinc-100 bg-zinc-50/50 px-5 py-2.5 text-xs text-zinc-600">
              Próximo vencimento:{" "}
              <strong className="text-zinc-900">
                {proximaParcela.vencimento ? formatarDia(proximaParcela.vencimento) : proximaParcela.quando}
              </strong>
              {" · "}faltam {formatMoney(Math.max(0, proximaParcela.valor - proximaParcela.pago))} desta parcela
            </div>
          )}
        </div>
      )}

      <div className="overflow-hidden rounded-xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)]">
        {activePayments.length === 0 ? (
          <div className="p-10 text-center flex flex-col items-center gap-3 text-zinc-400">
            <div className="w-12 h-12 rounded-full bg-zinc-50 flex items-center justify-center">
              <Wallet className="w-6 h-6 opacity-30" />
            </div>
            <p className="text-sm">Nenhum pagamento ativo registrado.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
          <table className="w-full min-w-[640px] table-fixed text-sm text-left">
            <colgroup>
              <col className="w-[130px]" />
              <col className="w-[96px]" />
              <col />
              <col className="w-[150px]" />
              <col className="w-[112px]" />
            </colgroup>
            <thead className="border-b border-zinc-100 bg-zinc-50/70 text-xs uppercase text-zinc-500">
              <tr>
                <th className="px-6 py-4 font-semibold tracking-wider">Data</th>
                <th className="px-6 py-4 font-semibold tracking-wider">Forma</th>
                <th className="px-6 py-4 font-semibold tracking-wider">Observacao</th>
                <th className="px-6 py-4 font-semibold tracking-wider text-right">Valor</th>
                <th className="px-6 py-4 font-semibold text-right w-[140px]">Acoes</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {activePayments.map((payment) => (
                <tr key={payment.id} className="group hover:bg-zinc-50/50 transition-colors">
                  <td className="px-6 py-4 text-zinc-600 whitespace-nowrap">
                    {new Date(payment.payment_date).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
                  </td>
                  <td className="px-6 py-4 font-medium text-zinc-900">
                    <div className="flex items-center gap-2 cursor-help w-fit" title={methodLabels[payment.payment_method] || payment.payment_method}>
                      {methodIcons[payment.payment_method] || <Wallet className="w-5 h-5 text-zinc-400" />}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex min-w-0 items-center gap-2.5">
                      <span className="min-w-0 flex-1 truncate text-zinc-500" title={payment.notes || "-"}>
                        {payment.notes || "-"}
                      </span>
                      <button
                        type="button"
                        onClick={() => openPaymentNoteModal(payment)}
                        className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-zinc-400 transition-all hover:bg-zinc-100 hover:text-[var(--ks-color-primary)]"
                        title="Ver observação"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-right font-bold text-emerald-600 whitespace-nowrap">
                    {formatMoney(Number(payment.amount))}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center justify-end gap-1.5 whitespace-nowrap">
                      <button
                        type="button"
                        onClick={() => handleIssueReceipt(payment)}
                        disabled={issuingReceiptId === payment.id}
                        className="inline-flex h-9 w-9 items-center justify-center rounded-full text-zinc-400 transition-all hover:bg-[rgba(68,37,167,0.08)] hover:text-[var(--ks-color-primary)] disabled:cursor-not-allowed disabled:opacity-50"
                        title="Emitir recibo"
                      >
                        {issuingReceiptId === payment.id ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <FileText className="w-4 h-4" />
                        )}
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDelete(payment.id)}
                        disabled={!canWrite || deletingId === payment.id}
                        className={[
                          "inline-flex h-9 w-9 items-center justify-center rounded-full transition-all",
                          canWrite ? "text-zinc-300 hover:bg-red-50 hover:text-red-500" : "text-zinc-200 cursor-not-allowed",
                        ].join(" ")}
                        title="Reverter pagamento"
                      >
                        {deletingId === payment.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        )}
      </div>

      {isFullyPaid && activePayments.length > 0 ? (
        <div className="flex justify-end">
          <button
            type="button"
            onClick={() => void handleIssueTotalReceipt()}
            disabled={issuingReceiptId === "__total__"}
            className="inline-flex h-11 items-center justify-center gap-2 rounded-xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)] px-4 text-sm font-semibold text-[var(--ks-color-primary)] transition-all hover:border-[rgba(68,37,167,0.24)] hover:bg-[rgba(68,37,167,0.04)] disabled:cursor-not-allowed disabled:opacity-60"
          >
            {issuingReceiptId === "__total__" ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileText className="w-4 h-4" />}
            Emitir Recibo do Valor Total
          </button>
        </div>
      ) : null}

      {canWrite ? (
        <PaymentModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          orderId={order.id}
          maxAmount={pending}
          onSuccess={onUpdate}
          initial={prefill}
        />
      ) : null}

      <Dialog open={Boolean(noteModalPayment)} onOpenChange={(open) => !open && closePaymentNoteModal()}>
        <DialogContent className="max-w-md">
          <DialogHeader className="pr-8">
            <DialogTitle className="flex items-center justify-between gap-3 text-left">
              <span>Observação do pagamento</span>
              <button
                type="button"
                onClick={() => setIsEditingNote((current) => !current)}
                disabled={!canWrite || savingNote}
                className={[
                  "inline-flex h-8 w-8 items-center justify-center rounded-full transition-colors",
                  canWrite ? "bg-zinc-100 text-zinc-600 hover:bg-zinc-200" : "bg-zinc-50 text-zinc-300 cursor-not-allowed",
                ].join(" ")}
                title="Editar observação"
              >
                <Pencil className="w-4 h-4" />
              </button>
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-3">
            {isEditingNote ? (
              <>
                <textarea
                  value={noteDraft}
                  onChange={(event) => setNoteDraft(event.target.value)}
                  rows={5}
                  className="w-full resize-none rounded-xl border border-zinc-200 bg-zinc-50 px-4 py-3 text-sm text-zinc-700 outline-none transition-all focus:border-[var(--ks-color-primary)] focus:bg-white"
                  placeholder="Sem observação"
                />
                <div className="flex justify-end gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setNoteDraft(noteModalPayment?.notes || "");
                      setIsEditingNote(false);
                    }}
                    disabled={savingNote}
                    className="inline-flex h-10 items-center justify-center rounded-lg border border-zinc-200 bg-white px-4 text-sm font-medium text-zinc-600"
                  >
                    Cancelar
                  </button>
                  <button
                    type="button"
                    onClick={() => void handleSavePaymentNote()}
                    disabled={savingNote}
                    className="inline-flex h-10 items-center justify-center rounded-lg bg-[var(--ks-color-primary)] px-4 text-sm font-semibold text-white disabled:opacity-60"
                  >
                    {savingNote ? "Salvando..." : "Salvar"}
                  </button>
                </div>
              </>
            ) : (
              <div className="rounded-xl border border-zinc-100 bg-zinc-50 px-4 py-3 text-sm leading-relaxed text-zinc-700 whitespace-pre-wrap">
                {noteModalPayment?.notes?.trim() ? noteModalPayment.notes : "Sem observação."}
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
