import {
  Badge,
  DataTable,
  DocumentShell,
  KeyValueGrid,
  Section,
  type BadgeTone,
} from '@/lib/pdf/brand-kit';
import { stageLabelFor } from '@/lib/constants';

export interface InterestSummaryPdfProps {
  portName: string;
  logoBuffer: Buffer | null;
  interest: {
    id: string;
    pipelineStage?: string | null;
    leadCategory?: string | null;
    source?: string | null;
    eoiStatus?: string | null;
    contractStatus?: string | null;
    depositStatus?: string | null;
    dateFirstContact?: Date | string | null;
    dateLastContact?: Date | string | null;
    dateEoiSent?: Date | string | null;
    dateEoiSigned?: Date | string | null;
    dateContractSent?: Date | string | null;
    dateContractSigned?: Date | string | null;
    dateDepositReceived?: Date | string | null;
  };
  client: { fullName?: string | null };
  yacht: {
    name?: string | null;
    lengthFt?: string | null;
    lengthM?: string | null;
    widthFt?: string | null;
    draftFt?: string | null;
  } | null;
  berth: {
    mooringNumber?: string | null;
    area?: string | null;
    lengthFt?: string | null;
    price?: string | number | null;
    priceCurrency?: string | null;
    status?: string | null;
  } | null;
  timeline: Array<{
    createdAt: Date | string;
    action?: string | null;
    entityType?: string | null;
    fieldChanged?: string | null;
  }>;
}

const STAGE_TONE: Record<string, BadgeTone> = {
  enquiry: 'neutral',
  qualified: 'neutral',
  nurturing: 'neutral',
  eoi: 'accent',
  reservation: 'warning',
  deposit_paid: 'warning',
  contract: 'success',
};

function fmt(d: Date | string | null | undefined): string {
  if (!d) return '-';
  return new Date(d).toISOString().slice(0, 10);
}

export function InterestSummaryPdf({
  portName,
  logoBuffer,
  interest,
  client,
  yacht,
  berth,
  timeline,
}: InterestSummaryPdfProps) {
  const stage = stageLabelFor(interest.pipelineStage);
  const docMeta = `${client.fullName ?? 'Unknown client'} · stage: ${stage}`;

  return (
    <DocumentShell
      portName={portName}
      docTitle="Interest Summary"
      docMeta={docMeta}
      logoBuffer={logoBuffer}
    >
      <Section title="Status">
        <KeyValueGrid
          rows={[
            { label: 'Pipeline stage', value: stage.replace('_', ' ') },
            { label: 'Lead category', value: interest.leadCategory ?? '-' },
            { label: 'Source', value: interest.source ?? '-' },
            { label: 'EOI status', value: interest.eoiStatus ?? '-' },
            { label: 'Contract status', value: interest.contractStatus ?? '-' },
            { label: 'Deposit status', value: interest.depositStatus ?? '-' },
          ]}
        />
        <Badge text={stage.replace('_', ' ').toUpperCase()} tone={STAGE_TONE[stage] ?? 'neutral'} />
      </Section>

      <Section title="Client">
        <KeyValueGrid rows={[{ label: 'Name', value: client.fullName ?? '-' }]} />
      </Section>

      {yacht ? (
        <Section title="Yacht">
          <KeyValueGrid
            rows={[
              { label: 'Name', value: yacht.name ?? '-' },
              {
                label: 'Length',
                value: yacht.lengthFt
                  ? `${yacht.lengthFt}ft${yacht.lengthM ? ` / ${yacht.lengthM}m` : ''}`
                  : '-',
              },
              { label: 'Beam', value: yacht.widthFt ? `${yacht.widthFt}ft` : '-' },
              { label: 'Draft', value: yacht.draftFt ? `${yacht.draftFt}ft` : '-' },
            ]}
          />
        </Section>
      ) : null}

      {berth ? (
        <Section title="Primary berth">
          <KeyValueGrid
            rows={[
              { label: 'Mooring', value: berth.mooringNumber ?? '-' },
              { label: 'Area', value: berth.area ?? '-' },
              { label: 'Length', value: berth.lengthFt ? `${berth.lengthFt}ft` : '-' },
              {
                label: 'Price',
                value: berth.price
                  ? `${berth.priceCurrency ?? 'USD'} ${Number(berth.price).toLocaleString()}`
                  : '-',
              },
              { label: 'Status', value: berth.status ?? '-' },
            ]}
          />
        </Section>
      ) : null}

      <Section title="Milestones">
        <KeyValueGrid
          rows={[
            { label: 'First contact', value: fmt(interest.dateFirstContact) },
            { label: 'Last contact', value: fmt(interest.dateLastContact) },
            { label: 'EOI sent', value: fmt(interest.dateEoiSent) },
            { label: 'EOI signed', value: fmt(interest.dateEoiSigned) },
            { label: 'Contract sent', value: fmt(interest.dateContractSent) },
            { label: 'Contract signed', value: fmt(interest.dateContractSigned) },
            { label: 'Deposit received', value: fmt(interest.dateDepositReceived) },
          ]}
        />
      </Section>

      <Section title={`Recent timeline (${timeline.length})`}>
        <DataTable<{
          createdAt: Date | string;
          action?: string | null;
          entityType?: string | null;
          fieldChanged?: string | null;
        }>
          columns={[
            { header: 'When', flex: 1.5, render: (e) => fmt(e.createdAt) },
            { header: 'Action', flex: 2, render: (e) => e.action ?? '-' },
            { header: 'Entity', flex: 1.5, render: (e) => e.entityType ?? '-' },
            { header: 'Field', flex: 1.5, render: (e) => e.fieldChanged ?? '-' },
          ]}
          rows={timeline}
          emptyMessage="No timeline events."
        />
      </Section>
    </DocumentShell>
  );
}
