"use client";

import * as React from "react";
import { Page as PDFPage, Document as PDFDocument } from "@react-pdf/renderer";
import { pdfStyles } from "./pdf/SharedUI.js";
import { SimpleLayout } from "./pdf/SimpleLayout.js";

// Modules
import { FrontPageModule } from "./pdf/modules/FrontPageModule.js";
import { BriefingModule } from "./pdf/modules/BriefingModule.js";
import { SitemapModule } from "./pdf/modules/SitemapModule.js";
import { EstimationModule } from "./pdf/modules/EstimationModule.js";
import { TransparenzModule } from "./pdf/modules/TransparenzModule.js";
import { ClosingModule } from "./pdf/modules/CommonModules.js";

import { calculatePositions } from "../logic/pricing/calculator.js";

interface PDFProps {
    state: any;
    totalPrice: number;
    pricing: any;
    headerIcon?: string;
    footerLogo?: string;
}

export const EstimationPDF = ({
    state,
    totalPrice,
    pricing,
    headerIcon,
    footerLogo,
}: PDFProps) => {
    const date = new Date().toLocaleDateString("de-DE", {
        year: "numeric",
        month: "long",
        day: "numeric",
    });

    const positions = calculatePositions(state, pricing);

    const companyData = {
        name: "Marc Mintel",
        address1: "Georg-Meistermann-Straße 7",
        address2: "54586 Schüller",
        ustId: "DE367588065",
    };

    const commonProps = {
        state,
        date,
        icon: headerIcon,
        footerLogo,
        companyData,
    };

    let pageCounter = 1;
    const getPageNum = () => (pageCounter++).toString().padStart(2, "0");

    return (
        <PDFDocument title={`Angebot - ${state.companyName || "Projekt"}`}>
            <PDFPage size="A4" style={pdfStyles.titlePage}>
                <FrontPageModule state={state} headerIcon={headerIcon} date={date} />
            </PDFPage>

            <SimpleLayout {...commonProps} pageNumber={getPageNum()}>
                <BriefingModule state={state} />
            </SimpleLayout>

            {state.sitemap && state.sitemap.length > 0 && (
                <SimpleLayout {...commonProps} pageNumber={getPageNum()}>
                    <SitemapModule state={state} />
                </SimpleLayout>
            )}

            <SimpleLayout {...commonProps} pageNumber={getPageNum()}>
                <EstimationModule
                    state={state}
                    positions={positions}
                    totalPrice={totalPrice}
                    date={date}
                />
            </SimpleLayout>

            <SimpleLayout {...commonProps} pageNumber={getPageNum()}>
                <TransparenzModule pricing={pricing} />
            </SimpleLayout>

            <SimpleLayout {...commonProps} pageNumber={getPageNum()}>
                <ClosingModule />
            </SimpleLayout>
        </PDFDocument>
    );
};
