'use client';

import type { TreatmentPlan } from '@/lib/services/treatments';
import { PLAN_STATUS_LABELS } from '@/lib/services/treatments';
import { CLINIC_INFO } from '@/lib/clinic-info';
import { formatCents } from '@/lib/money';
import { formatCpf, formatDate, formatDateTime } from '@/components/app/ui';

/** Orçamento imprimível (Ctrl+P / "Imprimir"), usado no painel e no portal. */
export default function BudgetDocument({ plan }: { plan: TreatmentPlan }) {
  const items = plan.items.filter((i) => i.status !== 'cancelled');
  const installmentValue = plan.installments > 1 ? Math.floor(plan.totalCents / plan.installments) : null;

  return (
    <article className="df-document card border-0 shadow-sm">
      <div className="card-body p-4 p-md-5">
        <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">Orçamento nº {plan.id}</h1>
            <small className="text-muted d-block">
              Emitido em {formatDate(plan.proposedAt ?? plan.createdAt)}
            </small>
            <small className="text-muted d-block">Situação: {PLAN_STATUS_LABELS[plan.status]}</small>
          </div>
        </header>

        <section className="row g-3 mb-4">
          <div className="col-sm-6">
            <div className="small text-muted">Paciente</div>
            <div className="fw-semibold">{plan.patient?.fullName}</div>
            {plan.patient?.cpf && <small className="text-muted">CPF {formatCpf(plan.patient.cpf)}</small>}
          </div>
          <div className="col-sm-6">
            <div className="small text-muted">Dentista responsável</div>
            <div className="fw-semibold">{plan.dentist?.fullName}</div>
            {plan.dentist?.cro && (
              <small className="text-muted">
                CRO {plan.dentist.cro}-{plan.dentist.croState}
              </small>
            )}
          </div>
          <div className="col-12">
            <div className="small text-muted">Plano</div>
            <div className="fw-semibold">{plan.title}</div>
          </div>
        </section>

        <div className="table-responsive mb-4">
          <table className="table table-sm align-middle">
            <thead>
              <tr>
                <th scope="col">Procedimento</th>
                <th scope="col">Dente / faces</th>
                <th scope="col" className="text-end">Qtd.</th>
                <th scope="col" className="text-end">Unitário</th>
                <th scope="col" className="text-end">Total</th>
              </tr>
            </thead>
            <tbody>
              {items.map((item) => (
                <tr key={item.id}>
                  <td>{item.description}</td>
                  <td>
                    {item.tooth ?? '—'}
                    {item.surfaces ? ` (${item.surfaces})` : ''}
                  </td>
                  <td className="text-end">{item.quantity}</td>
                  <td className="text-end table-nowrap">{formatCents(item.unitPriceCents)}</td>
                  <td className="text-end table-nowrap">{formatCents(item.totalCents)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr>
                <td colSpan={4} className="text-end text-muted">Subtotal</td>
                <td className="text-end table-nowrap">{formatCents(plan.subtotalCents)}</td>
              </tr>
              {plan.discountCents > 0 && (
                <tr>
                  <td colSpan={4} className="text-end text-muted">Desconto</td>
                  <td className="text-end table-nowrap">− {formatCents(plan.discountCents)}</td>
                </tr>
              )}
              <tr>
                <th colSpan={4} className="text-end">Total</th>
                <th className="text-end table-nowrap fs-5">{formatCents(plan.totalCents)}</th>
              </tr>
            </tfoot>
          </table>
        </div>

        <section className="mb-4">
          <div className="small text-muted">Condição de pagamento</div>
          <div>
            {installmentValue
              ? `${plan.installments} parcelas mensais de aproximadamente ${formatCents(installmentValue)}`
              : 'À vista'}
          </div>
          {plan.validUntil && (
            <small className="text-muted">
              Orçamento válido até {formatDate(`${plan.validUntil}T12:00:00`)}.
            </small>
          )}
        </section>

        {plan.notes && (
          <section className="mb-4">
            <div className="small text-muted">Observações</div>
            <p className="mb-0" style={{ whiteSpace: 'pre-wrap' }}>
              {plan.notes}
            </p>
          </section>
        )}

        {plan.approvedAt ? (
          <p className="small border rounded p-3 mb-0">
            <i className="bi bi-shield-check me-1 text-success" aria-hidden="true" />
            Aprovado em {formatDateTime(plan.approvedAt)}{' '}
            {plan.approvalChannel === 'portal'
              ? 'pelo paciente, eletronicamente, no portal.'
              : 'presencialmente na clínica.'}
          </p>
        ) : (
          <div className="row g-5 pt-5">
            <div className="col-6 text-center">
              <div className="border-top pt-2 small">{plan.patient?.fullName}</div>
            </div>
            <div className="col-6 text-center">
              <div className="border-top pt-2 small">{plan.dentist?.fullName}</div>
            </div>
          </div>
        )}
      </div>
    </article>
  );
}
