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

import { Footer } from './Footer';
import { Header } from './Header';
import { PDF_TOKENS } from './tokens';

const styles = StyleSheet.create({
  page: {
    fontFamily: PDF_TOKENS.fonts.sans,
    color: PDF_TOKENS.colors.text,
    fontSize: PDF_TOKENS.sizes.body,
    backgroundColor: PDF_TOKENS.colors.surface,
    paddingBottom: PDF_TOKENS.spacing.pagePaddingBottom,
  },
  body: {
    paddingHorizontal: PDF_TOKENS.spacing.pagePadding,
    paddingTop: PDF_TOKENS.spacing.sectionGap,
    flexDirection: 'column',
    gap: PDF_TOKENS.spacing.sectionGap,
  },
});

export interface DocumentShellProps {
  portName: string;
  docTitle: string;
  docMeta?: string;
  logoBuffer: Buffer | null;
  /** ISO timestamp shown in footer. Defaults to render time. */
  generatedAt?: Date;
  /** Title shown in the PDF metadata (cmd+I in Preview). */
  pdfTitle?: string;
  /** Author shown in the PDF metadata. Defaults to port name. */
  pdfAuthor?: string;
  children: ReactNode;
}

export function DocumentShell({
  portName,
  docTitle,
  docMeta,
  logoBuffer,
  generatedAt,
  pdfTitle,
  pdfAuthor,
  children,
}: DocumentShellProps) {
  return (
    <Document
      title={pdfTitle ?? docTitle}
      author={pdfAuthor ?? portName}
      producer={`${portName} CRM`}
    >
      <Page size="A4" style={styles.page}>
        <Header portName={portName} docTitle={docTitle} meta={docMeta} logoBuffer={logoBuffer} />
        <View style={styles.body}>{children}</View>
        <Footer portName={portName} generatedAt={generatedAt} />
      </Page>
    </Document>
  );
}
