'use client'

/**
 * EHSuggestionPanel
 *
 * Panel for displaying Erwartungshorizont-based suggestions.
 * Uses RAG to find relevant passages from the linked EH.
 */

import { useState, useCallback } from 'react'
import type { AnnotationType } from '../types'
import { ANNOTATION_COLORS } from '../types'

interface EHSuggestion {
  id: string
  eh_id: string
  eh_title: string
  text: string
  score: number
  criterion: string
  source_chunk_index: number
  decrypted: boolean
}

interface EHSuggestionPanelProps {
  studentId: string
  klausurId: string
  hasEH: boolean
  apiBase: string
  onInsertSuggestion?: (text: string, criterion: string) => void
}

const CRITERIA = [
  { id: 'allgemein', label: 'Alle Kriterien' },
  { id: 'inhalt', label: 'Inhalt', color: '#16a34a' },
  { id: 'struktur', label: 'Struktur', color: '#9333ea' },
  { id: 'stil', label: 'Stil', color: '#ea580c' },
]

export default function EHSuggestionPanel({
  studentId,
  klausurId,
  hasEH,
  apiBase,
  onInsertSuggestion,
}: EHSuggestionPanelProps) {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [suggestions, setSuggestions] = useState<EHSuggestion[]>([])
  const [selectedCriterion, setSelectedCriterion] = useState<string>('allgemein')
  const [passphrase, setPassphrase] = useState('')
  const [needsPassphrase, setNeedsPassphrase] = useState(false)
  const [queryPreview, setQueryPreview] = useState<string | null>(null)

  const fetchSuggestions = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)

      const res = await fetch(`${apiBase}/api/v1/students/${studentId}/eh-suggestions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          criterion: selectedCriterion === 'allgemein' ? null : selectedCriterion,
          passphrase: passphrase || null,
          limit: 5,
        }),
      })

      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.detail || 'Fehler beim Laden der Vorschlaege')
      }

      const data = await res.json()

      if (data.needs_passphrase) {
        setNeedsPassphrase(true)
        setSuggestions([])
        setError(data.message)
      } else {
        setNeedsPassphrase(false)
        setSuggestions(data.suggestions || [])
        setQueryPreview(data.query_preview || null)

        if (data.suggestions?.length === 0) {
          setError(data.message || 'Keine passenden Vorschlaege gefunden')
        }
      }
    } catch (err) {
      console.error('Failed to fetch EH suggestions:', err)
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setLoading(false)
    }
  }, [apiBase, studentId, selectedCriterion, passphrase])

  const handleInsert = (suggestion: EHSuggestion) => {
    if (onInsertSuggestion) {
      onInsertSuggestion(suggestion.text, suggestion.criterion)
    }
  }

  if (!hasEH) {
    return (
      <div className="p-4 text-center">
        <div className="text-slate-400 mb-4">
          <svg className="w-12 h-12 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
            />
          </svg>
          <p className="text-sm">Kein Erwartungshorizont verknuepft</p>
          <p className="text-xs mt-1">Laden Sie einen EH in der RAG-Verwaltung hoch</p>
        </div>
        <a
          href="/ai/rag"
          className="inline-block px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700"
        >
          Zur RAG-Verwaltung
        </a>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col">
      {/* Criterion selector */}
      <div className="p-3 border-b border-slate-200 bg-slate-50">
        <div className="flex gap-1 flex-wrap">
          {CRITERIA.map((c) => (
            <button
              key={c.id}
              onClick={() => setSelectedCriterion(c.id)}
              className={`px-2 py-1 text-xs rounded transition-colors ${
                selectedCriterion === c.id
                  ? 'text-white'
                  : 'bg-slate-200 text-slate-600 hover:bg-slate-300'
              }`}
              style={
                selectedCriterion === c.id
                  ? { backgroundColor: c.color || '#6366f1' }
                  : undefined
              }
            >
              {c.label}
            </button>
          ))}
        </div>
      </div>

      {/* Passphrase input (if needed) */}
      {needsPassphrase && (
        <div className="p-3 bg-yellow-50 border-b border-yellow-200">
          <label className="block text-xs font-medium text-yellow-800 mb-1">
            EH-Passphrase (verschluesselt)
          </label>
          <div className="flex gap-2">
            <input
              type="password"
              value={passphrase}
              onChange={(e) => setPassphrase(e.target.value)}
              placeholder="Passphrase eingeben..."
              className="flex-1 px-2 py-1 text-sm border border-yellow-300 rounded focus:ring-2 focus:ring-yellow-500"
            />
            <button
              onClick={fetchSuggestions}
              disabled={!passphrase}
              className="px-3 py-1 text-xs bg-yellow-600 text-white rounded hover:bg-yellow-700 disabled:opacity-50"
            >
              Laden
            </button>
          </div>
        </div>
      )}

      {/* Fetch button */}
      <div className="p-3 border-b border-slate-200">
        <button
          onClick={fetchSuggestions}
          disabled={loading}
          className="w-full py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center justify-center gap-2"
        >
          {loading ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              Lade Vorschlaege...
            </>
          ) : (
            <>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
              EH-Vorschlaege laden
            </>
          )}
        </button>
      </div>

      {/* Query preview */}
      {queryPreview && (
        <div className="px-3 py-2 bg-slate-50 border-b border-slate-200">
          <div className="text-xs text-slate-500 mb-1">Basierend auf:</div>
          <div className="text-xs text-slate-700 italic truncate">&quot;{queryPreview}&quot;</div>
        </div>
      )}

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

      {/* Suggestions list */}
      <div className="flex-1 overflow-auto">
        {suggestions.length === 0 && !loading && !error && (
          <div className="p-4 text-center text-slate-400 text-sm">
            Klicken Sie auf &quot;EH-Vorschlaege laden&quot; um passende Stellen aus dem Erwartungshorizont zu
            finden.
          </div>
        )}

        {suggestions.map((suggestion, idx) => (
          <div
            key={suggestion.id}
            className="p-3 border-b border-slate-100 hover:bg-slate-50 transition-colors"
          >
            {/* Header */}
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="text-xs font-medium text-slate-500">#{idx + 1}</span>
                <span
                  className="px-1.5 py-0.5 text-[10px] rounded text-white"
                  style={{
                    backgroundColor:
                      ANNOTATION_COLORS[suggestion.criterion as AnnotationType] || '#6366f1',
                  }}
                >
                  {suggestion.criterion}
                </span>
                <span className="text-[10px] text-slate-400">
                  Relevanz: {Math.round(suggestion.score * 100)}%
                </span>
              </div>
              {!suggestion.decrypted && (
                <span className="text-[10px] text-yellow-600">Verschluesselt</span>
              )}
            </div>

            {/* Content */}
            <p className="text-sm text-slate-700 mb-2 line-clamp-4">{suggestion.text}</p>

            {/* Source */}
            <div className="flex items-center justify-between text-[10px] text-slate-400">
              <span>Quelle: {suggestion.eh_title}</span>
              {onInsertSuggestion && suggestion.decrypted && (
                <button
                  onClick={() => handleInsert(suggestion)}
                  className="px-2 py-1 bg-purple-100 text-purple-700 rounded hover:bg-purple-200"
                >
                  Im Gutachten verwenden
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
