import { Document, Page, View, Text, Image } from '@react-pdf/renderer';
import type { ReactNode } from 'react';

import { makeReportStyles } from './styles';
import type { ReportBranding } from './types';

interface BrandedReportPageProps {
  branding: ReportBranding;
  title: string;
  subtitle?: string;
  /** ISO date string rendered into the footer next to the port name. */
  generatedAt: string;
  children: ReactNode;
}

/**
 * Single-document wrapper used by every report kind. Renders one or
 * more pages; the outer `<Document>` carries metadata that lands in
 * the PDF's Document Information dictionary (title shows in the
 * macOS Quick Look filename strip and Adobe Reader's window chrome).
 *
 * Page numbering uses react-pdf's `render={({ pageNumber, totalPages })...}`
 * pattern so the footer numbers itself without us computing pages
 * ahead of time. The render-prop is the one place in this file
 * where we can't avoid mixing layout with data.
 */
export function BrandedReportDocument({
  branding,
  title,
  subtitle,
  generatedAt,
  children,
}: BrandedReportPageProps) {
  const styles = makeReportStyles(branding);
  return (
    <Document
      title={title}
      author={branding.portName}
      subject={subtitle ?? `${branding.portName} report`}
      creator="Port Nimara CRM"
      producer="Port Nimara CRM"
    >
      <Page size="A4" style={styles.page} wrap>
        {/* Header - logo + title + subtitle. Re-renders inside each
            page via `fixed` would duplicate the brand bar; instead we
            keep it as a non-fixed element so it lives at the very top
            of the first content page. Footer is `fixed` (bottom of
            every page). */}
        <View style={styles.header}>
          {branding.logoUrl ? (
            <Image src={branding.logoUrl} style={styles.logo} cache />
          ) : (
            // Empty placeholder keeps the title baseline stable when
            // no logo is configured. Width matches the logo so the
            // text starts in the same X coordinate either way.
            <View style={{ width: 28, height: 28 }} />
          )}
          <View style={styles.headerText}>
            <Text style={styles.title}>{title}</Text>
            {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}
          </View>
        </View>

        {children}

        {/* Footer is `fixed` so it lands on every page; the page
            number renderer runs once per page (the only piece of
            this document that knows page count). */}
        <View style={styles.footer} fixed>
          <Text>{branding.portName}</Text>
          <Text>Generated {new Date(generatedAt).toLocaleString('en-GB')}</Text>
          <Text render={({ pageNumber, totalPages }) => `Page ${pageNumber} of ${totalPages}`} />
        </View>
      </Page>
    </Document>
  );
}
