'use client'

import { useState } from 'react'
import { Zap, X, RefreshCw, History, CheckCircle2 } from 'lucide-react'
import { BACKEND_URL, DOMAIN_OPTIONS, COLLECTION_OPTIONS } from './helpers'

interface GeneratorModalProps {
  onClose: () => void
  onComplete: () => void
}

export function GeneratorModal({ onClose, onComplete }: GeneratorModalProps) {
  const [generating, setGenerating] = useState(false)
  const [genResult, setGenResult] = useState<Record<string, unknown> | null>(null)
  const [genDomain, setGenDomain] = useState('')
  const [genMaxControls, setGenMaxControls] = useState(10)
  const [genDryRun, setGenDryRun] = useState(true)
  const [genCollections, setGenCollections] = useState<string[]>([])
  const [showJobHistory, setShowJobHistory] = useState(false)
  const [jobHistory, setJobHistory] = useState<Array<Record<string, unknown>>>([])

  const handleGenerate = async () => {
    setGenerating(true)
    setGenResult(null)
    try {
      const res = await fetch(`${BACKEND_URL}?endpoint=generate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          domain: genDomain || null,
          collections: genCollections.length > 0 ? genCollections : null,
          max_controls: genMaxControls,
          dry_run: genDryRun,
          skip_web_search: false,
        }),
      })
      if (!res.ok) {
        const err = await res.json()
        setGenResult({ status: 'error', message: err.error || err.details || 'Fehler' })
        return
      }
      const data = await res.json()
      setGenResult(data)
      if (!genDryRun) {
        onComplete()
      }
    } catch {
      setGenResult({ status: 'error', message: 'Netzwerkfehler' })
    } finally {
      setGenerating(false)
    }
  }

  const loadJobHistory = async () => {
    try {
      const res = await fetch(`${BACKEND_URL}?endpoint=generate-jobs`)
      if (res.ok) {
        const data = await res.json()
        setJobHistory(data.jobs || [])
      }
    } catch { /* ignore */ }
  }

  const toggleCollection = (col: string) => {
    setGenCollections(prev =>
      prev.includes(col) ? prev.filter(c => c !== col) : [...prev, col]
    )
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 mx-4 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Zap className="w-5 h-5 text-amber-600" />
            <h2 className="text-lg font-semibold text-gray-900">Control Generator</h2>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => { setShowJobHistory(!showJobHistory); if (!showJobHistory) loadJobHistory() }}
              className="text-gray-400 hover:text-gray-600"
              title="Job-Verlauf"
            >
              <History className="w-5 h-5" />
            </button>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {showJobHistory ? (
          <div className="space-y-3">
            <h3 className="text-sm font-medium text-gray-700">Letzte Generierungs-Jobs</h3>
            {jobHistory.length === 0 ? (
              <p className="text-sm text-gray-400">Keine Jobs vorhanden.</p>
            ) : (
              <div className="space-y-2 max-h-80 overflow-y-auto">
                {jobHistory.map((job, i) => (
                  <div key={i} className="border border-gray-200 rounded-lg p-3 text-xs">
                    <div className="flex items-center justify-between mb-1">
                      <span className={`px-2 py-0.5 rounded font-medium ${
                        job.status === 'completed' ? 'bg-green-100 text-green-700' :
                        job.status === 'failed' ? 'bg-red-100 text-red-700' :
                        job.status === 'running' ? 'bg-blue-100 text-blue-700' :
                        'bg-gray-100 text-gray-600'
                      }`}>
                        {String(job.status)}
                      </span>
                      <span className="text-gray-400">{String(job.created_at || '').slice(0, 16)}</span>
                    </div>
                    <div className="grid grid-cols-3 gap-1 text-gray-500 mt-1">
                      <span>Chunks: {String(job.total_chunks_scanned || 0)}</span>
                      <span>Generiert: {String(job.controls_generated || 0)}</span>
                      <span>Verifiziert: {String(job.controls_verified || 0)}</span>
                    </div>
                  </div>
                ))}
              </div>
            )}
            <button
              onClick={() => setShowJobHistory(false)}
              className="w-full py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              Zurueck zum Generator
            </button>
          </div>
        ) : (
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Domain (optional)</label>
              <select value={genDomain} onChange={e => setGenDomain(e.target.value)} className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg">
                <option value="">Alle Domains</option>
                {DOMAIN_OPTIONS.map(d => (
                  <option key={d.value} value={d.value}>{d.label}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-600 mb-2">Collections (optional)</label>
              <div className="grid grid-cols-2 gap-1.5">
                {COLLECTION_OPTIONS.map(col => (
                  <label key={col.value} className="flex items-center gap-2 text-xs text-gray-700 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={genCollections.includes(col.value)}
                      onChange={() => toggleCollection(col.value)}
                      className="rounded border-gray-300"
                    />
                    {col.label}
                  </label>
                ))}
              </div>
              {genCollections.length === 0 && (
                <p className="text-xs text-gray-400 mt-1">Keine Auswahl = alle Collections</p>
              )}
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Max. Controls: {genMaxControls}</label>
              <input
                type="range" min="1" max="100" step="1"
                value={genMaxControls}
                onChange={e => setGenMaxControls(parseInt(e.target.value))}
                className="w-full"
              />
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="dryRun"
                checked={genDryRun}
                onChange={e => setGenDryRun(e.target.checked)}
                className="rounded border-gray-300"
              />
              <label htmlFor="dryRun" className="text-sm text-gray-700">Dry Run (Vorschau ohne Speicherung)</label>
            </div>

            <button
              onClick={handleGenerate}
              disabled={generating}
              className="w-full py-2 text-sm text-white bg-amber-600 rounded-lg hover:bg-amber-700 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {generating ? (
                <><RefreshCw className="w-4 h-4 animate-spin" /> Generiere...</>
              ) : (
                <><Zap className="w-4 h-4" /> Generierung starten</>
              )}
            </button>

            {/* Results */}
            {genResult && (
              <div className={`p-4 rounded-lg text-sm ${genResult.status === 'error' ? 'bg-red-50 text-red-800' : 'bg-green-50 text-green-800'}`}>
                <div className="flex items-center gap-2 mb-1">
                  {genResult.status !== 'error' && <CheckCircle2 className="w-4 h-4" />}
                  <p className="font-medium">{String(genResult.message || genResult.status)}</p>
                </div>
                {genResult.status !== 'error' && (
                  <div className="grid grid-cols-2 gap-1 text-xs mt-2">
                    <span>Chunks gescannt: {String(genResult.total_chunks_scanned)}</span>
                    <span>Controls generiert: {String(genResult.controls_generated)}</span>
                    <span>Verifiziert: {String(genResult.controls_verified)}</span>
                    <span>Review noetig: {String(genResult.controls_needs_review)}</span>
                    <span>Zu aehnlich: {String(genResult.controls_too_close)}</span>
                    <span>Duplikate: {String(genResult.controls_duplicates_found)}</span>
                  </div>
                )}
                {Array.isArray(genResult.errors) && (genResult.errors as string[]).length > 0 && (
                  <div className="mt-2 text-xs text-red-600">
                    {(genResult.errors as string[]).slice(0, 3).map((e, i) => <p key={i}>{e}</p>)}
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
