'use client'

import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { useSDK } from '@/lib/sdk'
import { useEinwilligungen, EinwilligungenProvider } from '@/lib/sdk/einwilligungen/context'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { LegalTemplateResult } from '@/lib/sdk/types'
import { DataPointsPreview } from './components/DataPointsPreview'
import { DocumentValidation } from './components/DocumentValidation'
import { generateAllPlaceholders } from '@/lib/sdk/document-generator/datapoint-helpers'
import { loadAllTemplates } from './searchTemplates'
import { TemplateContext, EMPTY_CONTEXT } from './contextBridge'
import { CATEGORIES } from './_constants'
import { getGeneratorDefaults, getProfileLabel } from './scopeDefaults'
import TemplateLibrary from './_components/TemplateLibrary'
import GeneratorSection from './_components/GeneratorSection'
import RecommendedDocuments from './_components/RecommendedDocuments'
import { LifecycleFilter, filterTemplatesByStage } from './_components/LifecycleFilter'
import BulkGenerateModal from './_components/BulkGenerateModal'
import type { LifecycleStage } from '@/lib/sdk/founding/template-categories'

function DocumentGeneratorPageInner() {
  const { state } = useSDK()
  const { selectedDataPointsData } = useEinwilligungen()

  // Library state
  const [allTemplates, setAllTemplates] = useState<LegalTemplateResult[]>([])
  const [isLoadingLibrary, setIsLoadingLibrary] = useState(true)
  const [activeCategory, setActiveCategory] = useState<string>('all')
  const [activeStage, setActiveStage] = useState<LifecycleStage | 'all'>('all')
  const [activeLanguage, setActiveLanguage] = useState<'all' | 'de' | 'en'>('all')
  const [librarySearch, setLibrarySearch] = useState('')
  const [expandedPreviewId, setExpandedPreviewId] = useState<string | null>(null)

  // Generator state
  const [activeTemplate, setActiveTemplate] = useState<LegalTemplateResult | null>(null)
  const [context, setContext] = useState<TemplateContext>(EMPTY_CONTEXT)
  const [extraPlaceholders, setExtraPlaceholders] = useState<Record<string, string>>({})
  const [enabledModules, setEnabledModules] = useState<string[]>([])
  const generatorRef = useRef<HTMLDivElement>(null)

  const [totalCount, setTotalCount] = useState<number>(0)
  const [showBulkGenerate, setShowBulkGenerate] = useState(false)

  // Load all templates on mount
  useEffect(() => {
    setIsLoadingLibrary(true)
    loadAllTemplates(200).then((templates) => {
      setAllTemplates(templates)
      setTotalCount(templates.length)
      setIsLoadingLibrary(false)
    })
  }, [])

  // Pre-fill context from company profile + SDK state
  useEffect(() => {
    if (state?.companyProfile) {
      const profile = state.companyProfile
      const p = profile as unknown as Record<string, string>
      setContext((prev) => ({
        ...prev,
        PROVIDER: {
          ...prev.PROVIDER,
          LEGAL_NAME:      profile.companyName   || prev.PROVIDER.LEGAL_NAME,
          LEGAL_FORM:      p.legalForm           || prev.PROVIDER.LEGAL_FORM,
          ADDRESS_LINE:    p.addressLine         || prev.PROVIDER.ADDRESS_LINE,
          POSTAL_CODE:     p.postalCode          || prev.PROVIDER.POSTAL_CODE,
          CITY:            p.city                || prev.PROVIDER.CITY,
          COUNTRY:         p.country             || prev.PROVIDER.COUNTRY,
          EMAIL:           p.email               || prev.PROVIDER.EMAIL,
          PHONE:           p.phone               || prev.PROVIDER.PHONE,
          WEBSITE_URL:     p.websiteUrl          || prev.PROVIDER.WEBSITE_URL,
          CEO_NAME:        p.representedByName   || p.ceoName || prev.PROVIDER.CEO_NAME,
          REGISTER_COURT:  p.registerCourt       || prev.PROVIDER.REGISTER_COURT,
          REGISTER_NUMBER: p.registerNumber      || prev.PROVIDER.REGISTER_NUMBER,
          VAT_ID:          p.vatId               || prev.PROVIDER.VAT_ID,
        },
        PRIVACY: {
          ...prev.PRIVACY,
          DPO_NAME:  profile.dpoName  || prev.PRIVACY.DPO_NAME,
          DPO_EMAIL: profile.dpoEmail || prev.PRIVACY.DPO_EMAIL,
          CONTACT_EMAIL: profile.dpoEmail || prev.PRIVACY.CONTACT_EMAIL,
          SUPERVISORY_AUTHORITY_NAME:    p.supervisoryAuthorityName    || prev.PRIVACY.SUPERVISORY_AUTHORITY_NAME,
          SUPERVISORY_AUTHORITY_ADDRESS: p.supervisoryAuthorityAddress || prev.PRIVACY.SUPERVISORY_AUTHORITY_ADDRESS,
        },
        FEATURES: {
          ...prev.FEATURES,
          DATA_SUBJECT_REQUEST_CHANNEL: p.email
            ? `per E-Mail an ${p.email}`
            : prev.FEATURES.DATA_SUBJECT_REQUEST_CHANNEL,
        },
      }))
    }
  }, [state?.companyProfile])

  // Pre-fill TOM/DPA context from Compliance Scope Engine
  useEffect(() => {
    const scopeLevel = state?.complianceScope?.decision?.determinedLevel
    if (scopeLevel) {
      const defaults = getGeneratorDefaults(scopeLevel, state?.companyProfile as never)
      setContext((prev) => ({
        ...prev,
        TOM: { ...prev.TOM, ...defaults.tom },
        DPA: { ...prev.DPA, ...defaults.dpa },
      }))
    }
  }, [state?.complianceScope?.decision?.determinedLevel, state?.companyProfile])

  // ── MODULE WIRING: Backend Banner-Config → CONSENT + FEATURES ────────────
  useEffect(() => {
    // Fetch real vendor/category data from backend if SDK state has no banner
    if (state?.cookieBanner) return // SDK state takes priority
    fetch('/api/sdk/v1/banner/admin/sites', { headers: { 'x-tenant-id': '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e' } })
      .then(r => r.json())
      .then((sites: Array<{ site_id: string }>) => {
        if (!sites?.length) return
        return fetch(`/api/sdk/v1/banner/config/${sites[0].site_id}`, { headers: { 'x-tenant-id': '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e' } })
      })
      .then(r => r?.json())
      .then(config => {
        if (!config?.vendors?.length) return
        const analytics = config.vendors.filter((v: { category_key: string }) => v.category_key === 'statistics' || v.category_key === 'analytics').map((v: { vendor_name: string }) => v.vendor_name)
        const marketing = config.vendors.filter((v: { category_key: string }) => v.category_key === 'marketing').map((v: { vendor_name: string }) => v.vendor_name)
        setContext(prev => ({
          ...prev,
          CONSENT: {
            ...prev.CONSENT,
            ANALYTICS_TOOLS: analytics.length > 0 ? analytics.join(', ') : prev.CONSENT.ANALYTICS_TOOLS,
            MARKETING_PARTNERS: marketing.length > 0 ? marketing.join(', ') : prev.CONSENT.MARKETING_PARTNERS,
          },
          FEATURES: { ...prev.FEATURES, CMP_NAME: 'BreakPilot CMP', CMP_LOGS_CONSENTS: true },
        }))
      })
      .catch(() => {})
  }, [state?.cookieBanner])

  // ── MODULE WIRING: CookieBanner SDK State → CONSENT + FEATURES ──────────
  useEffect(() => {
    const banner = state?.cookieBanner
    if (!banner) return
    const cats = banner.categories || []
    const analyticsTools = cats
      .filter((c) => c.id === 'analytics' || c.id === 'statistics')
      .flatMap((c) => c.cookies?.map((ck) => ck.name) ?? [])
    const marketingTools = cats
      .filter((c) => c.id === 'marketing')
      .flatMap((c) => c.cookies?.map((ck) => ck.name) ?? [])
    const hasFunctional = cats.some((c) => c.id === 'functional')

    setContext((prev) => ({
      ...prev,
      CONSENT: {
        ...prev.CONSENT,
        ANALYTICS_TOOLS: analyticsTools.length > 0 ? analyticsTools.join(', ') : prev.CONSENT.ANALYTICS_TOOLS,
        MARKETING_PARTNERS: marketingTools.length > 0 ? marketingTools.join(', ') : prev.CONSENT.MARKETING_PARTNERS,
      },
      FEATURES: {
        ...prev.FEATURES,
        CMP_NAME: 'BreakPilot CMP',
        CMP_LOGS_CONSENTS: true,
        HAS_FUNCTIONAL_COOKIES: hasFunctional || prev.FEATURES.HAS_FUNCTIONAL_COOKIES,
        CONSENT_WITHDRAWAL_PATH: 'Footer-Link "Cookie-Einstellungen"',
      },
    }))
  }, [state?.cookieBanner])

  // ── MODULE WIRING: Loeschfristen → PRIVACY retention ──────────────────────
  useEffect(() => {
    const policies = state?.retentionPolicies
    if (!policies || policies.length === 0) return
    const maxMonths = policies.reduce((max, p) => {
      const match = p.retentionPeriod?.match(/(\d+)\s*(Monat|Jahr|Tag)/i)
      if (!match) return max
      const val = parseInt(match[1], 10)
      const unit = match[2].toLowerCase()
      const months = unit.startsWith('jahr') ? val * 12 : unit.startsWith('tag') ? Math.ceil(val / 30) : val
      return Math.max(max, months)
    }, 0)
    if (maxMonths > 0) {
      setContext((prev) => ({
        ...prev,
        PRIVACY: { ...prev.PRIVACY, ANALYTICS_RETENTION_MONTHS: maxMonths },
      }))
    }
  }, [state?.retentionPolicies])

  // ── MODULE WIRING: UseCases → FEATURES flags ─────────────────────────────
  useEffect(() => {
    const useCases = state?.useCases
    if (!useCases || useCases.length === 0) return
    const allText = useCases.map((uc) => `${uc.name} ${uc.description}`).join(' ').toLowerCase()
    const hasAccount = allText.includes('account') || allText.includes('konto') || allText.includes('registrier')
    const hasPayments = allText.includes('zahlung') || allText.includes('payment') || allText.includes('stripe') || allText.includes('paypal')
    const hasNewsletter = allText.includes('newsletter') || allText.includes('mailchimp') || allText.includes('e-mail-marketing')
    const hasSocial = allText.includes('social') || allText.includes('linkedin') || allText.includes('facebook') || allText.includes('instagram')

    setContext((prev) => ({
      ...prev,
      FEATURES: {
        ...prev.FEATURES,
        HAS_ACCOUNT: hasAccount || prev.FEATURES.HAS_ACCOUNT,
        HAS_PAYMENTS: hasPayments || prev.FEATURES.HAS_PAYMENTS,
        HAS_NEWSLETTER: hasNewsletter || prev.FEATURES.HAS_NEWSLETTER,
        HAS_SOCIAL_MEDIA: hasSocial || prev.FEATURES.HAS_SOCIAL_MEDIA,
      },
    }))
  }, [state?.useCases])

  // Pre-fill extra placeholders from Einwilligungen data points
  useEffect(() => {
    if (selectedDataPointsData && selectedDataPointsData.length > 0) {
      const generated = generateAllPlaceholders(selectedDataPointsData, 'de')
      setExtraPlaceholders((prev) => ({ ...prev, ...generated }))
    }
  }, [selectedDataPointsData])

  // Filtered templates (computed) — Lifecycle + Category + Language + Search
  const filteredTemplates = useMemo(() => {
    const category = CATEGORIES.find((c: { key: string }) => c.key === activeCategory)
    // 1. Lifecycle-Phase Filter via Code-Registry (mapped auf templateType)
    const stageFiltered = filterTemplatesByStage(
      allTemplates.map(t => ({ ...t, document_type: t.templateType || '' })),
      activeStage
    )
    return stageFiltered.filter((t) => {
      if (category && category.types !== null) {
        if (!category.types.includes(t.templateType || '')) return false
      }
      if (activeLanguage !== 'all' && t.language !== activeLanguage) return false
      if (librarySearch.trim()) {
        const q = librarySearch.toLowerCase()
        const title = (t.documentTitle || '').toLowerCase()
        const type = (t.templateType || '').toLowerCase()
        if (!title.includes(q) && !type.includes(q)) return false
      }
      return true
    })
  }, [allTemplates, activeCategory, activeStage, activeLanguage, librarySearch])

  // Counts by stage for filter UI
  const countsByStage = useMemo(() => {
    const counts: Record<string, number> = { pre_founding: 0, founding: 0, startup: 0, kmu: 0, konzern: 0 }
    const stages: LifecycleStage[] = ['pre_founding', 'founding', 'startup', 'kmu', 'konzern']
    for (const t of allTemplates) {
      const docType = t.templateType || ''
      for (const s of stages) {
        if (filterTemplatesByStage([{ document_type: docType }], s).length) {
          counts[s]++
        }
      }
    }
    return counts
  }, [allTemplates])

  const handleUseTemplate = useCallback((t: LegalTemplateResult) => {
    setActiveTemplate(t)
    setExpandedPreviewId(null)
    setExtraPlaceholders({})
    setEnabledModules([])
    setTimeout(() => {
      generatorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }, 100)
  }, [])

  const handleContextChange = useCallback(
    (section: keyof TemplateContext, key: string, value: unknown) => {
      setContext((prev) => ({
        ...prev,
        [section]: { ...(prev[section] as unknown as Record<string, unknown>), [key]: value },
      }))
    },
    []
  )

  const handleInsertPlaceholder = useCallback((placeholder: string) => {
    if (!extraPlaceholders[placeholder]) {
      const generated = generateAllPlaceholders(selectedDataPointsData || [], 'de')
      const val = generated[placeholder as keyof typeof generated]
      if (val) {
        setExtraPlaceholders((prev) => ({ ...prev, [placeholder]: val }))
      }
    }
  }, [extraPlaceholders, selectedDataPointsData])

  const stepInfo = STEP_EXPLANATIONS['document-generator'] || {
    title: 'Dokumentengenerator',
    description: 'Generieren Sie rechtliche Dokumente aus lizenzkonformen Vorlagen',
    explanation: 'Der Dokumentengenerator nutzt frei lizenzierte Textbausteine um Datenschutzerklaerungen, AGB und andere rechtliche Dokumente zu erstellen.',
    tips: ['Wählen Sie eine Vorlage aus der Bibliothek aus', 'Füllen Sie die Platzhalter mit Ihren Unternehmensdaten'],
  }

  return (
    <div className="space-y-8">
      <StepHeader
        stepId="document-generator"
        title="Dokumentengenerator"
        description="Generieren Sie rechtliche Dokumente aus lizenzkonformen Vorlagen"
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      />

      <div className="px-4 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-700 flex items-start gap-2">
        <span className="font-semibold">Quellen &amp; Lizenz:</span>
        <span>
          Die 91 Standard-Vorlagen sind <strong>BreakPilot-Eigenwerke</strong> (Lizenzregel R3 — Identifier-Verweis,
          eigene Lizenz). Vorlagen mit gesetzlicher Grundlage (z.B. VVT nach Art. 30 DSGVO,
          Loeschkonzept nach Art. 17 DSGVO) zitieren die jeweilige Rechtsquelle als R1.{' '}
          <a href="/sdk/licenses" className="underline">Quellenverzeichnis</a>
        </span>
      </div>

      {/* Status bar */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-5">
          <div className="text-sm text-gray-500">Vorlagen gesamt</div>
          <div className="text-3xl font-bold text-gray-900">{totalCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-5">
          <div className="text-sm text-gray-500">Angezeigt</div>
          <div className="text-3xl font-bold text-purple-600">{filteredTemplates.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-5">
          <div className="text-sm text-gray-500">Aktive Vorlage</div>
          <div className="text-sm font-medium text-gray-900 mt-1 truncate">
            {activeTemplate ? activeTemplate.documentTitle : '—'}
          </div>
        </div>
      </div>

      {/* Lifecycle-Phase Filter */}
      <LifecycleFilter
        activeStage={activeStage}
        onChange={setActiveStage}
        countsByStage={countsByStage}
      />

      {/* Bulk-Generate-Knopf — alle empfohlenen Dokumente in einem Rutsch */}
      <div className="flex items-center justify-between bg-emerald-50 border border-emerald-200 rounded p-3">
        <div className="text-sm text-gray-700">
          <b>Alle empfohlenen Dokumente in einem Rutsch generieren.</b>
          <div className="text-xs text-gray-600 mt-0.5">
            Profil + Scope-Antworten werden gegen die Empfehlungs-Regeln ausgewertet —
            markierte Templates werden als Drafts v1.0 in die Document-Library angelegt.
          </div>
        </div>
        <button
          className="px-4 py-2 text-sm bg-emerald-600 text-white rounded hover:bg-emerald-700 whitespace-nowrap"
          onClick={() => setShowBulkGenerate(true)}
        >
          Empfohlene generieren →
        </button>
      </div>

      {/* Recommended documents based on scope profile */}
      <RecommendedDocuments
        allTemplates={allTemplates}
        onUseTemplate={handleUseTemplate}
      />

      <TemplateLibrary
        allTemplates={allTemplates}
        filteredTemplates={filteredTemplates}
        isLoadingLibrary={isLoadingLibrary}
        activeCategory={activeCategory}
        onCategoryChange={setActiveCategory}
        activeLanguage={activeLanguage}
        onLanguageChange={setActiveLanguage}
        librarySearch={librarySearch}
        onSearchChange={setLibrarySearch}
        expandedPreviewId={expandedPreviewId}
        onTogglePreview={(id) => setExpandedPreviewId((prev) => (prev === id ? null : id))}
        onUseTemplate={handleUseTemplate}
      />

      {activeTemplate && (
        <div ref={generatorRef} className="space-y-6">
          <GeneratorSection
            template={activeTemplate}
            context={context}
            onContextChange={handleContextChange}
            extraPlaceholders={extraPlaceholders}
            onExtraChange={(key, value) => setExtraPlaceholders((prev) => ({ ...prev, [key]: value }))}
            onClose={() => setActiveTemplate(null)}
            enabledModules={enabledModules}
            onModuleToggle={(mod, checked) =>
              setEnabledModules((prev) =>
                checked ? [...prev, mod] : prev.filter((m) => m !== mod)
              )
            }
          />

          {selectedDataPointsData && selectedDataPointsData.length > 0 && (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2">
                <DocumentValidation
                  dataPoints={selectedDataPointsData}
                  documentContent={activeTemplate.text}
                  language="de"
                  onInsertPlaceholder={handleInsertPlaceholder}
                />
              </div>
              <div className="lg:col-span-1">
                <DataPointsPreview
                  dataPoints={selectedDataPointsData}
                  onInsertPlaceholder={handleInsertPlaceholder}
                  language="de"
                />
              </div>
            </div>
          )}
        </div>
      )}

      {showBulkGenerate && (
        <BulkGenerateModal
          allTemplates={allTemplates}
          context={context}
          extraPlaceholders={extraPlaceholders}
          enabledModules={enabledModules}
          companyProfile={state.companyProfile ?? null}
          complianceScope={state.complianceScope ?? null}
          onClose={() => setShowBulkGenerate(false)}
        />
      )}
    </div>
  )
}

export default function DocumentGeneratorPage() {
  return (
    <EinwilligungenProvider>
      <DocumentGeneratorPageInner />
    </EinwilligungenProvider>
  )
}
