'use client';

import * as React from 'react';
import { Document, Page, Text, View, StyleSheet, Image } from '@react-pdf/renderer';

const styles = StyleSheet.create({
  page: {
    padding: 40,
    backgroundColor: '#ffffff',
    fontFamily: 'Helvetica',
    fontSize: 10,
    color: '#1a1a1a',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 40,
    borderBottom: 2,
    borderBottomColor: '#000000',
    paddingBottom: 20,
  },
  brand: {
    fontSize: 18,
    fontWeight: 'bold',
    letterSpacing: -0.5,
  },
  quoteInfo: {
    textAlign: 'right',
  },
  quoteTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  quoteDate: {
    fontSize: 9,
    color: '#666666',
  },
  recipientSection: {
    marginBottom: 30,
  },
  recipientLabel: {
    fontSize: 8,
    color: '#999999',
    textTransform: 'uppercase',
    marginBottom: 4,
  },
  recipientName: {
    fontSize: 12,
    fontWeight: 'bold',
  },
  recipientRole: {
    fontSize: 10,
    color: '#666666',
  },
  table: {
    display: 'flex',
    width: 'auto',
    marginBottom: 30,
  },
  tableHeader: {
    flexDirection: 'row',
    backgroundColor: '#f8fafc',
    borderBottom: 1,
    borderBottomColor: '#e2e8f0',
    paddingVertical: 8,
    paddingHorizontal: 12,
  },
  tableRow: {
    flexDirection: 'row',
    borderBottom: 1,
    borderBottomColor: '#f1f5f9',
    paddingVertical: 10,
    paddingHorizontal: 12,
    alignItems: 'flex-start',
  },
  colPos: { width: '8%' },
  colDesc: { width: '62%' },
  colQty: { width: '10%', textAlign: 'center' },
  colPrice: { width: '20%', textAlign: 'right' },
  
  headerText: {
    fontSize: 8,
    fontWeight: 'bold',
    color: '#64748b',
    textTransform: 'uppercase',
  },
  posText: { fontSize: 9, color: '#94a3b8' },
  itemTitle: { fontSize: 10, fontWeight: 'bold', marginBottom: 2 },
  itemDesc: { fontSize: 8, color: '#64748b', lineHeight: 1.4 },
  priceText: { fontSize: 10, fontWeight: 'bold' },

  summarySection: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: 10,
  },
  summaryTable: {
    width: '40%',
  },
  summaryRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 4,
  },
  totalRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 12,
    borderTop: 1,
    borderTopColor: '#000000',
    marginTop: 8,
  },
  totalLabel: { fontSize: 12, fontWeight: 'bold' },
  totalValue: { fontSize: 16, fontWeight: 'bold' },

  configSection: {
    marginTop: 20,
    padding: 20,
    backgroundColor: '#f8fafc',
    borderRadius: 8,
  },
  configTitle: {
    fontSize: 10,
    fontWeight: 'bold',
    marginBottom: 10,
    textTransform: 'uppercase',
    color: '#475569',
  },
  configGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 20,
  },
  configItem: {
    width: '45%',
    marginBottom: 10,
  },
  configLabel: { fontSize: 8, color: '#94a3b8', marginBottom: 2 },
  configValue: { fontSize: 9, color: '#1e293b' },

  qrSection: {
    marginTop: 30,
    alignItems: 'center',
    justifyContent: 'center',
  },
  qrImage: {
    width: 80,
    height: 80,
  },
  qrText: {
    fontSize: 7,
    color: '#94a3b8',
    marginTop: 5,
  },

  footer: {
    position: 'absolute',
    bottom: 30,
    left: 40,
    right: 40,
    borderTop: 1,
    borderTopColor: '#f1f5f9',
    paddingTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    fontSize: 8,
    color: '#94a3b8',
  },
  pageNumber: {
    position: 'absolute',
    bottom: 30,
    right: 40,
    fontSize: 8,
    color: '#94a3b8',
  }
});

interface PDFProps {
  state: any;
  totalPrice: number;
  monthlyPrice: number;
  totalPagesCount: number;
  pricing: any;
  qrCodeData?: string;
}

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

  const vibeLabels: Record<string, string> = {
    minimal: 'Minimalistisch',
    bold: 'Mutig & Laut',
    nature: 'Natürlich',
    tech: 'Technisch'
  };

  const deadlineLabels: Record<string, string> = {
    asap: 'So schnell wie möglich',
    '2-3-months': 'In 2-3 Monaten',
    '3-6-months': 'In 3-6 Monaten',
    flexible: 'Flexibel'
  };

  const assetLabels: Record<string, string> = {
    logo: 'Logo',
    styleguide: 'Styleguide',
    content_concept: 'Inhalts-Konzept',
    media: 'Bild/Video-Material',
    icons: 'Icons',
    illustrations: 'Illustrationen',
    fonts: 'Fonts'
  };

  const featureLabels: Record<string, string> = {
    blog_news: 'Blog / News',
    products: 'Produktbereich',
    jobs: 'Karriere / Jobs',
    refs: 'Referenzen / Cases',
    events: 'Events / Termine'
  };

  const functionLabels: Record<string, string> = {
    search: 'Suche',
    filter: 'Filter-Systeme',
    pdf: 'PDF-Export',
    forms: 'Erweiterte Formulare'
  };

  const apiLabels: Record<string, string> = {
    crm: 'CRM System',
    erp: 'ERP / Warenwirtschaft',
    stripe: 'Stripe / Payment',
    newsletter: 'Newsletter / Marketing',
    ecommerce: 'E-Commerce / Shop',
    hr: 'HR / Recruiting',
    realestate: 'Immobilien',
    calendar: 'Termine / Booking',
    social: 'Social Media Sync',
    maps: 'Google Maps / Places',
    auth: 'Auth-Provider'
  };

  const socialLabels: Record<string, string> = {
    instagram: 'Instagram',
    linkedin: 'LinkedIn',
    facebook: 'Facebook',
    twitter: 'Twitter / X',
    tiktok: 'TikTok',
    youtube: 'YouTube'
  };

  const positions = [];
  let pos = 1;

  if (state.projectType === 'website') {
    positions.push({
      pos: pos++,
      title: 'Basis Website Setup',
      desc: 'Projekt-Setup, Infrastruktur, Hosting-Bereitstellung, Grundstruktur & Design-Vorlage, technisches SEO-Basics, Analytics.',
      qty: 1,
      price: pricing.BASE_WEBSITE
    });

    const allPages = [...state.selectedPages.map((p: string) => p === 'Home' ? 'Startseite' : p), ...state.otherPages];
    positions.push({
      pos: pos++,
      title: 'Individuelle Seiten',
      desc: `Gestaltung und Umsetzung von ${totalPagesCount} individuellen Seiten-Layouts (${allPages.join(', ')}).`,
      qty: totalPagesCount,
      price: totalPagesCount * pricing.PAGE
    });

    if (state.features.length > 0 || state.otherFeatures.length > 0) {
      const allFeatures = [...state.features.map((f: string) => featureLabels[f] || f), ...state.otherFeatures];
      positions.push({
        pos: pos++,
        title: 'System-Module',
        desc: `Implementierung funktionaler Bereiche: ${allFeatures.join(', ')}. Inklusive Datenstruktur und Darstellung.`,
        qty: allFeatures.length,
        price: allFeatures.length * pricing.FEATURE
      });
    }

    if (state.functions.length > 0 || state.otherFunctions.length > 0) {
      const allFunctions = [...state.functions.map((f: string) => functionLabels[f] || f), ...state.otherFunctions];
      positions.push({
        pos: pos++,
        title: 'Logik-Funktionen',
        desc: `Erweiterte Funktionen: ${allFunctions.join(', ')}.`,
        qty: allFunctions.length,
        price: allFunctions.length * pricing.FUNCTION
      });
    }

    if (state.apiSystems.length > 0 || state.otherTech.length > 0) {
      const allApis = [...state.apiSystems.map((a: string) => apiLabels[a] || a), ...state.otherTech];
      positions.push({
        pos: pos++,
        title: 'Schnittstellen (API)',
        desc: `Anbindung externer Systeme zur Datensynchronisation: ${allApis.join(', ')}.`,
        qty: allApis.length,
        price: allApis.length * pricing.API_INTEGRATION
      });
    }

    if (state.cmsSetup) {
      positions.push({
        pos: pos++,
        title: 'Inhaltsverwaltung (CMS)',
        desc: 'Einrichtung eines Systems zur eigenständigen Pflege von Inhalten und Datensätzen.',
        qty: 1,
        price: pricing.CMS_SETUP + (state.features.length + state.otherFeatures.length) * pricing.CMS_CONNECTION_PER_FEATURE
      });
    }

    if (state.newDatasets > 0) {
      positions.push({
        pos: pos++,
        title: 'Inhaltspflege (Initial)',
        desc: `Manuelle Einpflege von ${state.newDatasets} Datensätzen (z.B. Produkte, Blogartikel).`,
        qty: state.newDatasets,
        price: state.newDatasets * pricing.NEW_DATASET
      });
    }

    if (state.visualStaging > 0) {
      positions.push({
        pos: pos++,
        title: 'Visuelle Inszenierung',
        desc: `Umsetzung von ${state.visualStaging} Hero-Stories, Scroll-Effekten oder speziell inszenierten Sektionen.`,
        qty: state.visualStaging,
        price: state.visualStaging * pricing.VISUAL_STAGING
      });
    }

    if (state.complexInteractions > 0) {
      positions.push({
        pos: pos++,
        title: 'Komplexe Interaktion',
        desc: `Umsetzung von ${state.complexInteractions} Konfiguratoren, Live-Previews oder mehrstufigen Auswahlprozessen.`,
        qty: state.complexInteractions,
        price: state.complexInteractions * pricing.COMPLEX_INTERACTION
      });
    }

    if (state.languagesCount > 1) {
      const factorPrice = totalPrice - (totalPrice / (1 + (state.languagesCount - 1) * 0.2));
      positions.push({
        pos: pos++,
        title: 'Mehrsprachigkeit',
        desc: `Erweiterung des Systems auf ${state.languagesCount} Sprachen (Struktur & Logik).`,
        qty: state.languagesCount,
        price: Math.round(factorPrice)
      });
    }
  } else {
    positions.push({
      pos: pos++,
      title: 'Web App / Software Entwicklung',
      desc: 'Individuelle Software-Entwicklung nach Aufwand. Abrechnung erfolgt auf Stundenbasis.',
      qty: 1,
      price: 0
    });
  }

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        <View style={styles.header}>
          <View>
            <Text style={styles.brand}>marc mintel</Text>
            <Text style={{ fontSize: 8, color: '#64748b', marginTop: 4 }}>Digital Systems & Design</Text>
          </View>
          <View style={styles.quoteInfo}>
            <Text style={styles.quoteTitle}>Kostenschätzung</Text>
            <Text style={styles.quoteDate}>{date}</Text>
            <Text style={[styles.quoteDate, { marginTop: 2 }]}>Projekt: {state.projectType === 'website' ? 'Website' : 'Web App'}</Text>
          </View>
        </View>

        <View style={styles.recipientSection}>
          <Text style={styles.recipientLabel}>Ansprechpartner</Text>
          <Text style={styles.recipientName}>{state.name || 'Interessent'}</Text>
          {state.companyName && <Text style={styles.recipientRole}>{state.companyName}</Text>}
          {state.role && <Text style={styles.recipientRole}>{state.role}</Text>}
          <Text style={styles.recipientRole}>{state.email}</Text>
        </View>

        <View style={styles.table}>
          <View style={styles.tableHeader}>
            <Text style={[styles.headerText, styles.colPos]}>Pos</Text>
            <Text style={[styles.headerText, styles.colDesc]}>Beschreibung</Text>
            <Text style={[styles.headerText, styles.colQty]}>Menge</Text>
            <Text style={[styles.headerText, styles.colPrice]}>Betrag</Text>
          </View>

          {positions.map((item, i) => (
            <View key={i} style={styles.tableRow}>
              <Text style={[styles.posText, styles.colPos]}>{item.pos}</Text>
              <View style={styles.colDesc}>
                <Text style={styles.itemTitle}>{item.title}</Text>
                <Text style={styles.itemDesc}>{item.desc}</Text>
              </View>
              <Text style={[styles.posText, styles.colQty]}>{item.qty}</Text>
              <Text style={[styles.priceText, styles.colPrice]}>
                {item.price > 0 ? `${item.price.toLocaleString()} €` : 'n. A.'}
              </Text>
            </View>
          ))}
        </View>

        <View style={styles.summarySection}>
          <View style={styles.summaryTable}>
            <View style={styles.summaryRow}>
              <Text style={{ color: '#64748b' }}>Zwischensumme (Netto)</Text>
              <Text>{totalPrice.toLocaleString()} €</Text>
            </View>
            <View style={styles.summaryRow}>
              <Text style={{ color: '#64748b' }}>Umsatzsteuer (0%)*</Text>
              <Text>0,00 €</Text>
            </View>
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>Gesamtsumme</Text>
              <Text style={styles.totalValue}>{totalPrice.toLocaleString()} €</Text>
            </View>
            <Text style={{ fontSize: 7, color: '#94a3b8', textAlign: 'right', marginTop: -4 }}>
              *Gemäß § 19 UStG wird keine Umsatzsteuer berechnet.
            </Text>
            {state.projectType === 'website' && (
              <View style={[styles.summaryRow, { marginTop: 15, borderTop: 1, borderTopColor: '#f1f5f9', paddingTop: 10 }]}>
                <Text style={{ color: '#64748b', fontSize: 9 }}>Betrieb & Hosting</Text>
                <Text style={{ fontSize: 9, fontWeight: 'bold' }}>{monthlyPrice.toLocaleString()} € / Monat</Text>
              </View>
            )}
          </View>
        </View>

        <View style={styles.footer}>
          <Text>marc@mintel.me</Text>
          <Text>mintel.me</Text>
          <Text>Digital Systems & Design</Text>
        </View>
        <Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} von ${totalPages}`} fixed />
      </Page>

      <Page size="A4" style={styles.page}>
        <View style={styles.header}>
          <View>
            <Text style={styles.brand}>marc mintel</Text>
          </View>
          <View style={styles.quoteInfo}>
            <Text style={styles.quoteTitle}>Projektdetails</Text>
          </View>
        </View>

        <View style={styles.configSection}>
          <Text style={styles.configTitle}>Konfiguration & Wünsche</Text>
          <View style={styles.configGrid}>
            {state.projectType === 'website' ? (
              <>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Thema</Text>
                  <Text style={styles.configValue}>{state.websiteTopic || 'Nicht angegeben'}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Design-Vibe</Text>
                  <Text style={styles.configValue}>{vibeLabels[state.designVibe] || state.designVibe}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Farbschema</Text>
                  <Text style={styles.configValue}>{state.colorScheme.join(', ')}</Text>
                </View>
              </>
            ) : (
              <>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Zielgruppe</Text>
                  <Text style={styles.configValue}>{state.targetAudience === 'internal' ? 'Internes Tool' : 'Kunden-Portal'}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Plattform</Text>
                  <Text style={styles.configValue}>{state.platformType.toUpperCase()}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Sicherheit</Text>
                  <Text style={styles.configValue}>{state.dataSensitivity === 'high' ? 'Sensibel' : 'Standard'}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Rollen</Text>
                  <Text style={styles.configValue}>{state.userRoles.join(', ') || 'Keine'}</Text>
                </View>
              </>
            )}
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Mitarbeiter</Text>
              <Text style={styles.configValue}>{state.employeeCount || 'Nicht angegeben'}</Text>
            </View>
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Bestehende Website</Text>
              <Text style={styles.configValue}>{state.existingWebsite || 'Keine'}</Text>
            </View>
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Bestehende Domain</Text>
              <Text style={styles.configValue}>{state.existingDomain || 'Keine'}</Text>
            </View>
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Wunsch-Domain</Text>
              <Text style={styles.configValue}>{state.wishedDomain || 'Keine'}</Text>
            </View>
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Zeitplan</Text>
              <Text style={styles.configValue}>{deadlineLabels[state.deadline] || state.deadline}</Text>
            </View>
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Assets vorhanden</Text>
              <Text style={styles.configValue}>{state.assets.map((a: string) => assetLabels[a] || a).join(', ') || 'Keine angegeben'}</Text>
            </View>
            {state.otherAssets.length > 0 && (
              <View style={styles.configItem}>
                <Text style={styles.configLabel}>Weitere Assets</Text>
                <Text style={styles.configValue}>{state.otherAssets.join(', ')}</Text>
              </View>
            )}
            <View style={styles.configItem}>
              <Text style={styles.configLabel}>Sprachen</Text>
              <Text style={styles.configValue}>{state.languagesCount} ({state.languagesList.join(', ')})</Text>
            </View>
            {state.projectType === 'website' && (
              <>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>CMS (Inhaltsverwaltung)</Text>
                  <Text style={styles.configValue}>{state.cmsSetup ? 'Ja' : 'Nein'}</Text>
                </View>
                <View style={styles.configItem}>
                  <Text style={styles.configLabel}>Änderungsfrequenz</Text>
                  <Text style={styles.configValue}>
                    {state.expectedAdjustments === 'low' ? 'Selten' :
                     state.expectedAdjustments === 'medium' ? 'Regelmäßig' : 'Häufig'}
                  </Text>
                </View>
              </>
            )}
          </View>

          {state.socialMedia.length > 0 && (
            <View style={{ marginTop: 15 }}>
              <Text style={styles.configLabel}>Social Media Accounts</Text>
              {state.socialMedia.map((id: string) => (
                <Text key={id} style={[styles.configValue, { lineHeight: 1.4 }]}>
                  {socialLabels[id] || id}: {state.socialMediaUrls[id] || 'Keine URL angegeben'}
                </Text>
              ))}
            </View>
          )}

          {state.designWishes && (
            <View style={{ marginTop: 15 }}>
              <Text style={styles.configLabel}>Design-Vorstellungen</Text>
              <Text style={[styles.configValue, { lineHeight: 1.4 }]}>{state.designWishes}</Text>
            </View>
          )}

          {state.references.length > 0 && (
            <View style={{ marginTop: 15 }}>
              <Text style={styles.configLabel}>Referenzen</Text>
              <Text style={[styles.configValue, { lineHeight: 1.4 }]}>{state.references.join('\n')}</Text>
            </View>
          )}

          {state.message && (
            <View style={{ marginTop: 15 }}>
              <Text style={styles.configLabel}>Nachricht / Anmerkungen</Text>
              <Text style={[styles.configValue, { lineHeight: 1.4 }]}>{state.message}</Text>
            </View>
          )}
        </View>

        {qrCodeData && (
          <View style={styles.qrSection}>
            <Image src={qrCodeData} style={styles.qrImage} />
            <Text style={styles.qrText}>QR-Code scannen, um Konfiguration online zu öffnen</Text>
          </View>
        )}

        <View style={styles.footer}>
          <Text>marc@mintel.me</Text>
          <Text>mintel.me</Text>
          <Text>Digital Systems & Design</Text>
        </View>
        <Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} von ${totalPages}`} fixed />
      </Page>
    </Document>
  );
};
