'use client';

import { useEffect, useState } from 'react';
import { getReceipt, PAYMENT_METHOD_LABELS, ReceiptDetail } from '@/lib/services/finance';
import { CLINIC_INFO } from '@/lib/clinic-info';
import { formatCents } from '@/lib/money';
import { BackLink, ErrorAlert, Loading, formatCpf, formatDateTime } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

/** Recibo imprimível — mesmo componente no painel e no portal. */
export default function ReceiptView({ id, backHref }: { id: number; backHref: string }) {
  const [receipt, setReceipt] = useState<ReceiptDetail | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getReceipt(id)
      .then(setReceipt)
      .catch((err) => setError(extractApiError(err)));
  }, [id]);

  if (error) return <ErrorAlert message={error} />;
  if (!receipt) return <Loading />;

  const cancelled = Boolean(receipt.cancelledAt);

  return (
    <>
      <div className="d-flex justify-content-between align-items-center no-print mb-3">
        <BackLink href={backHref} label="Voltar" />
        <button className="btn btn-primary" onClick={() => window.print()}>
          <i className="bi bi-printer me-1" />
          Imprimir / salvar PDF
        </button>
      </div>

      <article className="df-document card border-0 shadow-sm position-relative">
        <div className="card-body p-4 p-md-5">
          {cancelled && (
            <div className="alert alert-danger text-center fw-bold">
              RECIBO CANCELADO em {formatDateTime(receipt.cancelledAt)} (pagamento estornado)
            </div>
          )}
          <header className="d-flex flex-wrap justify-content-between gap-3 border-bottom pb-3 mb-4">
            <div>
              <div className="h4 fw-bold text-primary mb-1">
                <i className="bi bi-heart-pulse-fill me-2" aria-hidden="true" />
                DentalFlow
              </div>
              <small className="text-muted">
                {CLINIC_INFO.phone} · {CLINIC_INFO.email} · {CLINIC_INFO.city}
              </small>
            </div>
            <div className="text-md-end">
              <h1 className="h5 fw-bold mb-1">Recibo nº {receipt.number}</h1>
              <small className="text-muted">Emitido em {formatDateTime(receipt.issuedAt)}</small>
            </div>
          </header>

          <p className="fs-5 lh-lg">
            Recebemos de <strong>{receipt.patient.fullName}</strong>
            {receipt.patient.cpf && <>, CPF {formatCpf(receipt.patient.cpf)},</>} a importância de{' '}
            <strong>{formatCents(receipt.amountCents)}</strong>, referente a{' '}
            <strong>{receipt.payment.charge.description}</strong>.
          </p>

          <dl className="row small mb-5">
            <dt className="col-sm-3 text-muted fw-normal">Forma de pagamento</dt>
            <dd className="col-sm-9">{PAYMENT_METHOD_LABELS[receipt.payment.method]}</dd>
            <dt className="col-sm-3 text-muted fw-normal">Data do pagamento</dt>
            <dd className="col-sm-9">{formatDateTime(receipt.payment.paidAt)}</dd>
          </dl>

          <div className="row pt-4">
            <div className="col-sm-6 offset-sm-6 text-center">
              <div className="border-top pt-2 small">DentalFlow</div>
            </div>
          </div>
        </div>
      </article>
    </>
  );
}
