'use client'

import { useState, useEffect, useMemo } from 'react'
import { LegalTemplateResult } from '@/lib/sdk/types'
import {
  TemplateContext,
  contextToPlaceholders, getRelevantSections,
  getUncoveredPlaceholders, getMissingRequired,
} from '../contextBridge'
import {
  runRuleset, getDocType, applyBlockRemoval,
  buildBoolContext, applyConditionalBlocks,
  type RuleInput, type RuleEngineResult,
} from '../ruleEngine'
import { MODULE_LABELS } from '../_constants'
import GeneratorPlaceholdersTab from './GeneratorPlaceholdersTab'
import GeneratorPreviewTab from './GeneratorPreviewTab'

export default function GeneratorSection({
  template,
  context,
  onContextChange,
  extraPlaceholders,
  onExtraChange,
  onClose,
  enabledModules,
  onModuleToggle,
}: {
  template: LegalTemplateResult
  context: TemplateContext
  onContextChange: (section: keyof TemplateContext, key: string, value: unknown) => void
  extraPlaceholders: Record<string, string>
  onExtraChange: (key: string, value: string) => void
  onClose: () => void
  enabledModules: string[]
  onModuleToggle: (mod: string, checked: boolean) => void
}) {
  const [activeTab, setActiveTab] = useState<'placeholders' | 'preview'>('placeholders')
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['PROVIDER', 'LEGAL']))

  const placeholders = Array.isArray(template.placeholders) ? template.placeholders : []
  const relevantSections = useMemo(() => getRelevantSections(placeholders), [placeholders])
  const uncovered = useMemo(() => getUncoveredPlaceholders(placeholders, context), [placeholders, context])
  const missing = useMemo(() => getMissingRequired(placeholders, context), [placeholders, context])

  // Rule engine evaluation
  const ruleResult = useMemo((): RuleEngineResult | null => {
    if (!template) return null
    return runRuleset({
      doc_type: getDocType(template.templateType ?? '', template.language ?? 'de'),
      render: { lang: template.language ?? 'de', variant: 'standard' },
      context,
      modules: { enabled: enabledModules },
    } satisfies RuleInput)
  }, [template, context, enabledModules])

  const allPlaceholderValues = useMemo(() => ({
    ...contextToPlaceholders(ruleResult?.contextAfterDefaults ?? context),
    ...extraPlaceholders,
  }), [context, extraPlaceholders, ruleResult])

  // Boolean context for {{#IF}} rendering
  const boolCtx = useMemo(
    () => ruleResult ? buildBoolContext(ruleResult.contextAfterDefaults, ruleResult.computedFlags) : {},
    [ruleResult]
  )

  const renderedContent = useMemo(() => {
    // 1. Remove ruleset-driven blocks ([BLOCK:ID])
    let content = applyBlockRemoval(template.text, ruleResult?.removedBlocks ?? [])
    // 2. Evaluate {{#IF}} / {{#IF_NOT}} / {{#IF_ANY}} directives
    content = applyConditionalBlocks(content, boolCtx)
    // 3. Substitute placeholders
    for (const [key, value] of Object.entries(allPlaceholderValues)) {
      if (value) {
        content = content.replace(new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), value)
      }
    }
    return content
  }, [template.text, allPlaceholderValues, ruleResult, boolCtx])

  // Compute which modules are relevant (mentioned in violations/warnings)
  const relevantModules = useMemo(() => {
    if (!ruleResult) return []
    const mentioned = new Set<string>()
    const allIssues = [...ruleResult.violations, ...ruleResult.warnings]
    for (const issue of allIssues) {
      if (issue.phase === 'module_requirements') {
        // Extract module ID from message
        for (const modId of Object.keys(MODULE_LABELS)) {
          if (issue.message.includes(modId)) mentioned.add(modId)
        }
      }
    }
    // Also show modules that are enabled but not mentioned
    for (const mod of enabledModules) {
      if (mod in MODULE_LABELS) mentioned.add(mod)
    }
    return [...mentioned]
  }, [ruleResult, enabledModules])

  const handleCopy = () => navigator.clipboard.writeText(renderedContent)

  const [saveStatus, setSaveStatus] = useState<string | null>(null)

  const handleSaveToWorkflow = async () => {
    setSaveStatus('saving')
    try {
      // 1. Create or find document
      const docRes = await fetch('/api/sdk/v1/compliance/legal-documents/documents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: template.templateType || 'custom',
          name: template.documentTitle || 'Dokument',
          description: `Generiert aus Template: ${template.templateType}`,
        }),
      })
      if (!docRes.ok) throw new Error('Dokument konnte nicht erstellt werden')
      const doc = await docRes.json()

      // 2. Create version
      const verRes = await fetch('/api/sdk/v1/compliance/legal-documents/versions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          document_id: doc.id,
          title: template.documentTitle || 'Dokument',
          content: renderedContent,
          language: template.language || 'de',
          version: '1.0',
        }),
      })
      if (!verRes.ok) throw new Error('Version konnte nicht erstellt werden')
      setSaveStatus('saved')
      setTimeout(() => setSaveStatus(null), 3000)
    } catch (e) {
      setSaveStatus('error')
      setTimeout(() => setSaveStatus(null), 3000)
    }
  }

  const handleExportMarkdown = () => {
    const blob = new Blob([renderedContent], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${(template.documentTitle || 'dokument').replace(/\s+/g, '-').toLowerCase()}.md`
    a.click()
    URL.revokeObjectURL(url)
  }

  const toggleSection = (sec: string) => {
    setExpandedSections((prev) => {
      const next = new Set(prev)
      if (next.has(sec)) next.delete(sec)
      else next.add(sec)
      return next
    })
  }

  // Auto-expand all relevant sections on first render
  useEffect(() => {
    if (relevantSections.length > 0) {
      setExpandedSections(new Set(relevantSections))
    }
  }, [template.id]) // eslint-disable-line react-hooks/exhaustive-deps

  // Computed flags pills config
  const flagPills: { key: string; label: string; color: string }[] = ruleResult ? [
    { key: 'IS_B2C',          label: 'B2C',           color: 'bg-blue-100 text-blue-700' },
    { key: 'SERVICE_IS_SAAS', label: 'SaaS',           color: 'bg-green-100 text-green-700' },
    { key: 'HAS_PENALTY',     label: 'Vertragsstrafe', color: 'bg-orange-100 text-orange-700' },
    { key: 'HAS_ANALYTICS',   label: 'Analytics',      color: 'bg-gray-100 text-gray-600' },
  ] : []

  return (
    <div className="bg-white rounded-xl border-2 border-purple-300 overflow-hidden">
      {/* Header */}
      <div className="bg-purple-50 px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3 flex-wrap">
          <svg className="w-5 h-5 text-purple-600 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
          </svg>
          <div>
            <div className="text-xs text-purple-500 font-medium uppercase tracking-wide">Generator</div>
            <div className="font-semibold text-gray-900 text-sm">{template.documentTitle}</div>
          </div>
          {/* Computed flags pills */}
          {ruleResult && (
            <div className="flex gap-1.5 flex-wrap">
              {flagPills.map(({ key, label, color }) =>
                (ruleResult.computedFlags as unknown as Record<string, boolean>)[key] ? (
                  <span key={key} className={`px-2 py-0.5 text-[10px] font-medium rounded-full ${color}`}>
                    {label}
                  </span>
                ) : null
              )}
            </div>
          )}
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <button
            onClick={() => {
              // Load example data for current template type
              const templateType = template.templateType || ''
              const lang = template.language || 'de'
              const exampleFile = `/sdk/document-generator/examples/${templateType}_${lang}.json`
              fetch(exampleFile)
                .then(r => r.ok ? r.json() : null)
                .then(data => {
                  if (!data?.context) return
                  const ctx = data.context
                  for (const [section, fields] of Object.entries(ctx)) {
                    if (typeof fields === 'object' && fields) {
                      for (const [key, value] of Object.entries(fields as Record<string, unknown>)) {
                        onContextChange(section as keyof TemplateContext, key, value)
                      }
                    }
                  }
                })
                .catch(() => {/* no example available */})
            }}
            className="px-3 py-1 text-xs bg-blue-50 text-blue-600 border border-blue-200 rounded-lg hover:bg-blue-100 transition-colors"
          >
            Beispieldaten
          </button>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition-colors shrink-0" aria-label="Schließen">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      {/* Tab bar */}
      <div className="flex border-b border-gray-200 px-6">
        {(['placeholders', 'preview'] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${
              activeTab === tab
                ? 'text-purple-600 border-purple-600'
                : 'text-gray-500 border-transparent hover:text-gray-700'
            }`}
          >
            {tab === 'placeholders' ? 'Kontext ausfüllen' : 'Vorschau & Export'}
            {tab === 'placeholders' && missing.length > 0 && (
              <span className="ml-2 px-1.5 py-0.5 text-[10px] bg-orange-100 text-orange-600 rounded-full">
                {missing.length}
              </span>
            )}
            {tab === 'preview' && ruleResult && ruleResult.violations.length > 0 && (
              <span className="ml-2 px-1.5 py-0.5 text-[10px] bg-red-100 text-red-600 rounded-full">
                {ruleResult.violations.length}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="p-6">
        {activeTab === 'placeholders' && (
          <GeneratorPlaceholdersTab
            placeholders={placeholders}
            relevantSections={relevantSections}
            uncovered={uncovered}
            missing={missing}
            expandedSections={expandedSections}
            toggleSection={toggleSection}
            context={context}
            onContextChange={onContextChange}
            extraPlaceholders={extraPlaceholders}
            onExtraChange={onExtraChange}
            relevantModules={relevantModules}
            enabledModules={enabledModules}
            onModuleToggle={onModuleToggle}
            onGotoPreview={() => setActiveTab('preview')}
          />
        )}

        {activeTab === 'preview' && (
          <GeneratorPreviewTab
            template={template}
            ruleResult={ruleResult}
            renderedContent={renderedContent}
            missing={missing}
            onCopy={handleCopy}
            onExportMarkdown={handleExportMarkdown}
            onSaveToWorkflow={handleSaveToWorkflow}
            saveStatus={saveStatus}
          />
        )}
      </div>
    </div>
  )
}
