import React from 'react';

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

import PdfDocumentTitle from '@/components/pdf/PdfDocumentTitle';
import PdfHeader from '@/components/pdf/PdfHeader';
import { pdfStyles } from '@/components/pdf/PdfStyles';
import { htmlToPdfParagraphSegments } from '@/components/pdf/pdfUtils';

type CreatorTextSection = {
  title?: string;
  subtitle?: string | null;
  content: string;
};

interface CreatorTextPDFDocumentProps {
  creatorName: string;
  creatorProfession?: string;
  sections: CreatorTextSection[];
}

const CreatorTextPDFDocument: React.FC<CreatorTextPDFDocumentProps> = ({
  creatorName,
  creatorProfession = '',
  sections,
}) => {
  const documentTitle = sections.length === 1 ? sections[0]?.title : null;
  const shouldRenderSectionTitles = sections.length > 1;

  return (
    <Document>
      <Page size="A4" style={pdfStyles.page}>
        <PdfHeader title={creatorName} subtitle={creatorProfession} />
        <PdfDocumentTitle title={documentTitle || ''} />

        {sections.map((section, index) => {
          const paragraphs = htmlToPdfParagraphSegments(section.content);
          const subtitle = section.subtitle?.trim();

          return (
            <View key={`${section.title || 'section'}-${index}`} style={pdfStyles.contentBlock}>
              {shouldRenderSectionTitles && section.title && (
                <Text style={pdfStyles.contentTitle}>{section.title}</Text>
              )}
              {subtitle && <Text style={pdfStyles.contentSubtitle}>{subtitle}</Text>}
              {paragraphs.map((paragraphSegments, index) => (
                <Text key={`${section.title}-${index}`} style={pdfStyles.bodyText}>
                  {paragraphSegments.map((segment, segmentIndex) => (
                    <Text
                      key={`${section.title}-${index}-${segmentIndex}`}
                      style={segment.isBold ? pdfStyles.label : undefined}
                    >
                      {segment.text}
                    </Text>
                  ))}
                </Text>
              ))}
            </View>
          );
        })}
      </Page>
    </Document>
  );
};

export default CreatorTextPDFDocument;
