import { DataTable, DocumentShell, KeyValueGrid, Section } from '@/lib/pdf/brand-kit';

export interface ParentCompanyRow {
  date: string;
  establishment: string;
  category: string;
  amountEur: number;
}

export interface ParentCompanyExpensePdfProps {
  portName: string;
  logoBuffer: Buffer | null;
  rows: ParentCompanyRow[];
  subtotal: number;
  managementFee: number;
  total: number;
  /** Optional ISO date range for the meta line. */
  dateFrom?: string;
  dateTo?: string;
  /** Whether the EUR rate lookup succeeded. Renders a small footnote if false. */
  rateAvailable?: boolean;
}

function fmtEur(n: number): string {
  return `EUR ${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

export function ParentCompanyExpensePdf({
  portName,
  logoBuffer,
  rows,
  subtotal,
  managementFee,
  total,
  dateFrom,
  dateTo,
  rateAvailable = true,
}: ParentCompanyExpensePdfProps) {
  const meta =
    dateFrom || dateTo
      ? `Range: ${dateFrom ?? '-'} → ${dateTo ?? 'today'} · ${rows.length} entries`
      : `${rows.length} entries`;

  return (
    <DocumentShell
      portName={portName}
      docTitle="Parent Company Expense Report (EUR)"
      docMeta={meta}
      logoBuffer={logoBuffer}
    >
      <Section title="Summary">
        <KeyValueGrid
          rows={[
            { label: 'Entries', value: rows.length },
            { label: 'Subtotal', value: fmtEur(subtotal) },
            { label: 'Management fee (5%)', value: fmtEur(managementFee) },
            { label: 'Total', value: fmtEur(total) },
          ]}
        />
        {!rateAvailable ? (
          <Section title="Note">
            <KeyValueGrid
              rows={[
                {
                  label: 'Currency conversion',
                  value:
                    'EUR exchange rate unavailable at generation time - amounts shown at 1:1 USD:EUR fallback.',
                },
              ]}
              layout="stacked"
            />
          </Section>
        ) : null}
      </Section>

      <Section title="Entries">
        <DataTable<ParentCompanyRow>
          columns={[
            { header: 'Date', flex: 1, render: (r) => r.date },
            { header: 'Establishment', flex: 3, render: (r) => r.establishment },
            { header: 'Category', flex: 2, render: (r) => r.category },
            { header: 'Amount', flex: 2, align: 'right', render: (r) => fmtEur(r.amountEur) },
          ]}
          rows={rows}
          totals={['Total', '', '', fmtEur(total)]}
          emptyMessage="No expenses in the selected range."
        />
      </Section>
    </DocumentShell>
  );
}
