'use client'

import React, { useState } from 'react'
import { ChecklistView } from './ChecklistView'
import { ResultsTabsView } from './ResultsTabsView'
import { PreScanWizard, useScanContext, isContextComplete } from './PreScanWizard'
import { safeSetItem } from './storageHelpers'

interface DocEntry {
  id: string
  type: string
  label: string
  url: string
  text: string       // P-Paste: User kopiert Doc-Text direkt rein
  mode: 'url' | 'text'  // welcher Input wird aktiv genutzt
}

const DOC_TYPES = [
  { id: 'dse', label: 'Datenschutzerklärung / DSI' },
  { id: 'cookie', label: 'Cookie-Richtlinie' },
  { id: 'impressum', label: 'Impressum' },
  { id: 'agb', label: 'AGB' },
  { id: 'nutzungsbedingungen', label: 'Nutzungsbedingungen' },
  { id: 'widerruf', label: 'Widerrufsbelehrung' },
  { id: 'social_media', label: 'DSE Social Media (Art. 26)' },
  { id: 'dsfa', label: 'DSFA (Art. 35)' },
  { id: 'dsa', label: 'DSA / Digital Services Act' },
  { id: 'legal_notice', label: 'Rechtliche Hinweise (IP, Forward-Looking)' },
  { id: 'lizenzhinweise', label: 'Lizenzhinweise Dritter (OSS)' },
  { id: 'other', label: 'Sonstiges' },
]

function newEntry(): DocEntry {
  return { id: crypto.randomUUID().slice(0, 8), type: 'dse', label: '',
            url: '', text: '', mode: 'url' }
}

export function DocCheckTab() {
  const [scanContext, setScanContext] = useScanContext()
  const [entries, setEntries] = useState<DocEntry[]>(() => {
    if (typeof window === 'undefined') return [newEntry()]
    try { const s = localStorage.getItem('doc-check-entries'); return s ? JSON.parse(s) : [newEntry()] } catch { return [newEntry()] }
  })
  const [checkCookieBanner, setCheckCookieBanner] = useState(false)
  const [useAgent, setUseAgent] = useState(false)
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState('')
  const [results, setResults] = useState<any>(() => {
    if (typeof window === 'undefined') return null
    try { const s = localStorage.getItem('doc-check-results'); return s ? JSON.parse(s) : null } catch { return null }
  })
  const [error, setError] = useState<string | null>(null)
  const [history, setHistory] = useState<{ date: string; urls: number; findings: number; resultKey: string }[]>(() => {
    if (typeof window === 'undefined') return []
    try { return JSON.parse(localStorage.getItem('doc-check-history') || '[]') } catch { return [] }
  })

  // Persist entries
  React.useEffect(() => { localStorage.setItem('doc-check-entries', JSON.stringify(entries)) }, [entries])

  const updateEntry = (id: string, field: keyof DocEntry, value: string) => {
    setEntries(prev => prev.map(e => e.id === id ? { ...e, [field]: value } : e))
  }

  const removeEntry = (id: string) => {
    setEntries(prev => prev.filter(e => e.id !== id))
  }

  const addEntry = () => {
    setEntries(prev => [...prev, newEntry()])
  }

  // Auto-detect label from URL
  const autoLabel = (entry: DocEntry) => {
    if (entry.label) return
    try {
      const path = new URL(entry.url).pathname
      const last = path.split('/').filter(Boolean).pop() || ''
      const label = last.replace(/-\d+$/, '').replace(/-/g, ' ')
        .replace(/\b\w/g, c => c.toUpperCase())
      if (label.length > 3) {
        updateEntry(entry.id, 'label', label)
      }
    } catch { /* invalid URL */ }
  }

  const handleSubmit = async () => {
    const validEntries = entries.filter(e => e.url.trim() || e.text.trim())
    if (validEntries.length === 0) return

    setLoading(true)
    setError(null)
    setResults(null)
    setProgress('Pruefung wird gestartet...')

    try {
      const startRes = await fetch('/api/sdk/v1/agent/doc-check', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entries: validEntries.map(e => ({
            doc_type: e.type,
            label: e.label
                   || (e.url ? e.url.split('/').pop() : '')
                   || `${e.type}-paste`,
            url:  e.mode === 'text' ? '' : e.url.trim(),
            // Backend nimmt text > url. Wenn beide gefuellt sind und
            // mode='url', schicken wir den text NICHT mit.
            text: e.mode === 'text' ? e.text.trim() : '',
          })),
          check_cookie_banner: checkCookieBanner,
          use_agent: useAgent,
          scan_context: scanContext,
        }),
      })
      if (!startRes.ok) throw new Error(`Pruefung konnte nicht gestartet werden: ${startRes.status}`)
      const { check_id } = await startRes.json()
      if (!check_id) throw new Error('Keine Check-ID erhalten')

      // Poll for results
      let attempts = 0
      while (attempts < 120) {
        await new Promise(r => setTimeout(r, 3000))
        const pollRes = await fetch(`/api/sdk/v1/agent/doc-check?check_id=${check_id}`)
        if (!pollRes.ok) { attempts++; continue }
        const pollData = await pollRes.json()
        if (pollData.progress) setProgress(pollData.progress)
        if (pollData.status === 'completed' && pollData.result) {
          setResults(pollData.result)
          setProgress('')
          safeSetItem('doc-check-results', JSON.stringify(pollData.result))
          const resultKey = `doc-check-result-${Date.now()}`
          safeSetItem(resultKey, JSON.stringify(pollData.result))
          const entry = { date: new Date().toISOString(), urls: validEntries.length, findings: pollData.result.total_findings || 0, resultKey }
          const updated = [entry, ...history].slice(0, 30)
          setHistory(updated)
          safeSetItem('doc-check-history', JSON.stringify(updated))
          break
        }
        if (pollData.status === 'failed') {
          throw new Error(pollData.error || 'Pruefung fehlgeschlagen')
        }
        attempts++
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
      setProgress('')
    } finally {
      setLoading(false)
    }
  }

  const contextReady = isContextComplete(scanContext)

  return (
    <div className="space-y-4">
      {/* P79 Pre-Scan-Wizard — 8 Pflichtfelder */}
      <PreScanWizard value={scanContext} onChange={setScanContext} />

      {/* URL / Text Entries */}
      <div className="space-y-3">
        {entries.map((entry, i) => (
          <div key={entry.id} className="space-y-1.5">
            <div className="flex items-center gap-2">
              <select
                value={entry.type}
                onChange={e => updateEntry(entry.id, 'type', e.target.value)}
                className="w-48 px-3 py-2.5 border border-gray-300 rounded-lg text-sm bg-white shrink-0"
              >
                {DOC_TYPES.map(t => (
                  <option key={t.id} value={t.id}>{t.label}</option>
                ))}
              </select>
              <input
                type="text"
                value={entry.label}
                onChange={e => updateEntry(entry.id, 'label', e.target.value)}
                placeholder={entry.type === 'other' ? 'Dokumentname' : 'Version / Stand (optional)'}
                className="w-40 px-3 py-2.5 border border-gray-300 rounded-lg text-sm shrink-0"
              />

              {/* Mode-Toggle URL / Text */}
              <div className="inline-flex border border-gray-300 rounded-lg overflow-hidden text-xs shrink-0">
                <button type="button"
                  onClick={() => updateEntry(entry.id, 'mode', 'url')}
                  className={`px-3 py-2 ${entry.mode === 'url'
                    ? 'bg-purple-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
                  URL
                </button>
                <button type="button"
                  onClick={() => updateEntry(entry.id, 'mode', 'text')}
                  className={`px-3 py-2 ${entry.mode === 'text'
                    ? 'bg-purple-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
                  Text einfügen
                </button>
              </div>

              {entry.mode === 'url' && (
                <input
                  type="url"
                  value={entry.url}
                  onChange={e => updateEntry(entry.id, 'url', e.target.value)}
                  onBlur={() => autoLabel(entry)}
                  placeholder="https://example.com/datenschutz"
                  className="flex-1 px-3 py-2.5 border border-gray-300 rounded-lg text-sm"
                />
              )}

              {entries.length > 1 && (
                <button onClick={() => removeEntry(entry.id)}
                  className="p-2 text-gray-400 hover:text-red-500 shrink-0">
                  <svg className="w-4 h-4" 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>

            {entry.mode === 'text' && (
              <div className="ml-[400px]">
                <textarea
                  value={entry.text}
                  onChange={e => updateEntry(entry.id, 'text', e.target.value)}
                  placeholder={
                    entry.type === 'cookie'
                      ? 'Kopiere hier die komplette Cookie-Tabelle rein (Tab-getrennt oder mit | als Trenner — wir parsen alle Spalten deterministisch)…'
                      : 'Kopiere hier den vollständigen Doc-Text rein. Wir erkennen automatisch ob es zu „' + (DOC_TYPES.find(t => t.id === entry.type)?.label ?? entry.type) + '" passt.'
                  }
                  className="w-full h-32 px-3 py-2 border border-gray-300 rounded-lg text-xs font-mono resize-y"
                />
                <div className="text-[10px] text-gray-500 mt-1">
                  {entry.text.trim().length > 0
                    ? `${entry.text.trim().length.toLocaleString('de-DE')} Zeichen · ${entry.text.trim().split(/\s+/).length.toLocaleString('de-DE')} Wörter`
                    : 'Der Crawler wird übersprungen — die Analyse läuft direkt auf dem eingefügten Text.'}
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Add URL + Options */}
      <div className="flex items-center justify-between">
        <button onClick={addEntry}
          className="flex items-center gap-1.5 text-sm text-purple-600 hover:text-purple-700 font-medium">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          URL hinzufuegen
        </button>

        <label className="flex items-center gap-2 text-sm text-gray-600">
          <input
            type="checkbox"
            checked={checkCookieBanner}
            onChange={e => setCheckCookieBanner(e.target.checked)}
            className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
          />
          Cookie-Banner pruefen
        </label>

        <button
          type="button"
          onClick={() => setUseAgent(!useAgent)}
          className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
            useAgent
              ? 'bg-emerald-100 border-emerald-300 text-emerald-800'
              : 'bg-gray-50 border-gray-200 text-gray-500 hover:bg-gray-100'
          }`}
        >
          <span className={`w-2 h-2 rounded-full ${useAgent ? 'bg-emerald-500' : 'bg-gray-300'}`} />
          {useAgent ? 'KI-Agent aktiv (1.874 MCs)' : 'KI-Agent aus'}
        </button>
      </div>

      {/* Submit */}
      <button
        onClick={handleSubmit}
        disabled={loading
                  || entries.every(e => !e.url.trim() && !e.text.trim())
                  || !contextReady}
        className="w-full px-4 py-3 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 disabled:opacity-50 transition-colors text-sm flex items-center justify-center gap-2"
        title={!contextReady ? 'Bitte zuerst die 8 Pflichtfelder ausfüllen' : undefined}
      >
        {loading ? (
          <>
            <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
            Pruefe...
          </>
        ) : !contextReady ? (
          `Klassifizierung unvollständig (8 Pflichtfelder)`
        ) : (
          `${entries.filter(e => e.url.trim()).length} Dokument${entries.filter(e => e.url.trim()).length !== 1 ? 'e' : ''} pruefen`
        )}
      </button>

      {/* Progress */}
      {progress && (
        <div className="bg-purple-50 border border-purple-200 rounded-lg p-3 text-sm text-purple-700 flex items-center gap-3">
          <svg className="animate-spin w-4 h-4 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          {progress}
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">{error}</div>
      )}

      {/* Results — als Tab-Ansicht (Übersicht/Cookies/DSE/Impressum/AGB/Banner/Mail) */}
      {results && results.results && (
        <ResultsTabsView results={results} />
      )}

      {/* History */}
      {history.length > 0 && (
        <div className="border border-gray-200 rounded-xl p-4">
          <h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Pruefungen</h4>
          <div className="space-y-1">
            {history.map((h, i) => (
              <button key={i} onClick={() => {
                if (h.resultKey) {
                  try {
                    const saved = localStorage.getItem(h.resultKey)
                    if (saved) { setResults(JSON.parse(saved)); return }
                  } catch {}
                }
                // Fallback: load last result
                try {
                  const last = localStorage.getItem('doc-check-results')
                  if (last) setResults(JSON.parse(last))
                } catch {}
              }}
                className="w-full flex items-center justify-between text-sm py-2 px-2 rounded-lg border border-gray-50 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left">
                <span className="text-gray-600">
                  {new Date(h.date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                </span>
                <div className="flex items-center gap-3">
                  <span className="text-xs text-gray-500">{h.urls} Dok.</span>
                  <span className={`text-xs font-medium ${h.findings > 0 ? 'text-amber-600' : 'text-green-600'}`}>
                    {h.findings} Findings
                  </span>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
