import {
  DataTable,
  DocumentShell,
  KeyValueGrid,
  PieChart,
  Section,
  type PieDatum,
} from '@/lib/pdf/brand-kit';
import { PDF_TOKENS } from '@/lib/pdf/brand-kit';
import type { OccupancyData } from '@/lib/services/report-generators';

export interface OccupancyReportPdfProps {
  portName: string;
  logoBuffer: Buffer | null;
  data: OccupancyData;
}

// Mirrors BERTH_STATUSES in src/lib/constants.ts (canonical 3-status
// enum). 'reserved' and 'maintenance' were dropped from the schema; if
// pre-migration data still carries them, the label falls back to the
// raw status string via the `?? status` guard at the call site below.
const STATUS_LABELS: Record<string, string> = {
  available: 'Available',
  under_offer: 'Under offer',
  sold: 'Sold',
};

const STATUS_COLORS: Record<string, string> = {
  available: PDF_TOKENS.colors.success,
  under_offer: PDF_TOKENS.colors.warning,
  sold: PDF_TOKENS.colors.accentBlue,
};

export function OccupancyReportPdf({ portName, logoBuffer, data }: OccupancyReportPdfProps) {
  const entries = Object.entries(data.statusCounts);
  const pieData: PieDatum[] = entries.map(([status, count]) => ({
    label: STATUS_LABELS[status] ?? status,
    value: count,
    color: STATUS_COLORS[status],
  }));

  const sold = data.statusCounts.sold ?? 0;
  const underOffer = data.statusCounts.under_offer ?? 0;
  const available = data.statusCounts.available ?? 0;
  const occupiedRate = `${Math.round(data.occupancyRate * 100)}%`;

  return (
    <DocumentShell portName={portName} docTitle="Occupancy Report" logoBuffer={logoBuffer}>
      <Section title="Summary">
        <KeyValueGrid
          rows={[
            { label: 'Total berths', value: data.totalBerths.toLocaleString() },
            { label: 'Occupancy rate', value: occupiedRate },
            { label: 'Sold', value: sold.toLocaleString() },
            { label: 'Under offer', value: underOffer.toLocaleString() },
            { label: 'Available', value: available.toLocaleString() },
          ]}
        />
      </Section>

      <Section title="Status mix" subtitle="Berth count by current status.">
        <PieChart data={pieData} innerRadiusRatio={0.5} />
      </Section>

      <Section title="Status breakdown">
        <DataTable<{ status: string; count: number }>
          columns={[
            { header: 'Status', flex: 2, render: (r) => STATUS_LABELS[r.status] ?? r.status },
            {
              header: 'Count',
              flex: 1,
              align: 'right',
              render: (r) => r.count.toLocaleString(),
            },
            {
              header: '% of total',
              flex: 1,
              align: 'right',
              render: (r) =>
                data.totalBerths > 0 ? `${((r.count / data.totalBerths) * 100).toFixed(1)}%` : '-',
            },
          ]}
          rows={entries.map(([status, count]) => ({ status, count }))}
          totals={['Total', String(data.totalBerths), '100%']}
        />
      </Section>
    </DocumentShell>
  );
}
