'use client'

import { useEffect, useState } from 'react'
import {
  getModules, getMatrix, getAssignments, getStats, getDeadlines, getModuleMedia,
  getAuditLog, generateContent, generateQuiz,
  publishContent, checkEscalation, getContent,
  generateAllContent, generateAllQuizzes,
} from '@/lib/sdk/training/api'
import type {
  TrainingModule, TrainingAssignment,
  MatrixResponse, TrainingStats, DeadlineInfo, AuditLogEntry, ModuleContent, TrainingMedia, VideoScript,
} from '@/lib/sdk/training/types'
import {
  REGULATION_LABELS, REGULATION_COLORS, FREQUENCY_LABELS,
  STATUS_LABELS, STATUS_COLORS, ROLE_LABELS, ALL_ROLES,
} from '@/lib/sdk/training/types'
import AudioPlayer from '@/components/training/AudioPlayer'
import VideoPlayer from '@/components/training/VideoPlayer'
import ScriptPreview from '@/components/training/ScriptPreview'
type Tab = 'overview' | 'modules' | 'matrix' | 'assignments' | 'content' | 'audit'

export default function TrainingPage() {
  const [activeTab, setActiveTab] = useState<Tab>('overview')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [stats, setStats] = useState<TrainingStats | null>(null)
  const [modules, setModules] = useState<TrainingModule[]>([])
  const [matrix, setMatrix] = useState<MatrixResponse | null>(null)
  const [assignments, setAssignments] = useState<TrainingAssignment[]>([])
  const [deadlines, setDeadlines] = useState<DeadlineInfo[]>([])
  const [auditLog, setAuditLog] = useState<AuditLogEntry[]>([])

  const [selectedModuleId, setSelectedModuleId] = useState<string>('')
  const [generatedContent, setGeneratedContent] = useState<ModuleContent | null>(null)
  const [generating, setGenerating] = useState(false)
  const [bulkGenerating, setBulkGenerating] = useState(false)
  const [bulkResult, setBulkResult] = useState<{ generated: number; skipped: number; errors: string[] } | null>(null)
  const [moduleMedia, setModuleMedia] = useState<TrainingMedia[]>([])

  const [statusFilter, setStatusFilter] = useState<string>('')
  const [regulationFilter, setRegulationFilter] = useState<string>('')

  useEffect(() => {
    loadData()
  }, [])

  async function loadData() {
    setLoading(true)
    setError(null)
    try {
      const [statsRes, modulesRes, matrixRes, assignmentsRes, deadlinesRes, auditRes] = await Promise.allSettled([
        getStats(),
        getModules(),
        getMatrix(),
        getAssignments({ limit: 50 }),
        getDeadlines(10),
        getAuditLog({ limit: 30 }),
      ])

      if (statsRes.status === 'fulfilled') setStats(statsRes.value)
      if (modulesRes.status === 'fulfilled') setModules(modulesRes.value.modules)
      if (matrixRes.status === 'fulfilled') setMatrix(matrixRes.value)
      if (assignmentsRes.status === 'fulfilled') setAssignments(assignmentsRes.value.assignments)
      if (deadlinesRes.status === 'fulfilled') setDeadlines(deadlinesRes.value.deadlines)
      if (auditRes.status === 'fulfilled') setAuditLog(auditRes.value.entries)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden')
    } finally {
      setLoading(false)
    }
  }

  async function handleGenerateContent() {
    if (!selectedModuleId) return
    setGenerating(true)
    try {
      const content = await generateContent(selectedModuleId)
      setGeneratedContent(content)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Content-Generierung')
    } finally {
      setGenerating(false)
    }
  }

  async function handleGenerateQuiz() {
    if (!selectedModuleId) return
    setGenerating(true)
    try {
      await generateQuiz(selectedModuleId, 5)
      await loadData()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Quiz-Generierung')
    } finally {
      setGenerating(false)
    }
  }

  async function handlePublishContent(contentId: string) {
    try {
      await publishContent(contentId)
      setGeneratedContent(null)
      await loadData()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Veroeffentlichen')
    }
  }

  async function handleCheckEscalation() {
    try {
      const result = await checkEscalation()
      alert(`Eskalation geprueft: ${result.total_checked} geprueft, ${result.escalated} eskaliert`)
      await loadData()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Eskalationspruefung')
    }
  }

  async function handleLoadContent(moduleId: string) {
    try {
      const content = await getContent(moduleId)
      setGeneratedContent(content)
    } catch {
      setGeneratedContent(null)
    }
  }

  async function handleBulkContent() {
    setBulkGenerating(true)
    setBulkResult(null)
    try {
      const result = await generateAllContent('de')
      setBulkResult({ generated: result.generated ?? 0, skipped: result.skipped ?? 0, errors: result.errors ?? [] })
      await loadData()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Bulk-Generierung')
    } finally {
      setBulkGenerating(false)
    }
  }

  async function loadModuleMedia(moduleId: string) {
    try {
      const result = await getModuleMedia(moduleId)
      setModuleMedia(result.media)
    } catch {
      setModuleMedia([])
    }
  }

  async function handleBulkQuiz() {
    setBulkGenerating(true)
    setBulkResult(null)
    try {
      const result = await generateAllQuizzes()
      setBulkResult({ generated: result.generated ?? 0, skipped: result.skipped ?? 0, errors: result.errors ?? [] })
      await loadData()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Bulk-Quiz-Generierung')
    } finally {
      setBulkGenerating(false)
    }
  }

  const tabs: { id: Tab; label: string }[] = [
    { id: 'overview', label: 'Uebersicht' },
    { id: 'modules', label: 'Modulkatalog' },
    { id: 'matrix', label: 'Training Matrix' },
    { id: 'assignments', label: 'Zuweisungen' },
    { id: 'content', label: 'Content-Generator' },
    { id: 'audit', label: 'Audit Trail' },
  ]

  const filteredModules = modules.filter(m =>
    (!regulationFilter || m.regulation_area === regulationFilter)
  )

  const filteredAssignments = assignments.filter(a =>
    (!statusFilter || a.status === statusFilter)
  )

  if (loading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/3"></div>
          <div className="grid grid-cols-4 gap-4">
            {[1,2,3,4].map(i => <div key={i} className="h-24 bg-gray-200 rounded"></div>)}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Compliance Training Engine</h1>
          <p className="text-sm text-gray-500 mt-1">
            Training-Module, Zuweisungen und Compliance-Schulungen verwalten
          </p>
        </div>
        <button
          onClick={handleCheckEscalation}
          className="px-4 py-2 text-sm bg-orange-50 text-orange-700 border border-orange-200 rounded-lg hover:bg-orange-100"
        >
          Eskalation pruefen
        </button>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
          {error}
          <button onClick={() => setError(null)} className="ml-2 underline">Schliessen</button>
        </div>
      )}

      {/* Tabs */}
      <div className="border-b border-gray-200">
        <nav className="flex -mb-px space-x-6">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && stats && (
        <div className="space-y-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <KPICard label="Module" value={stats.total_modules} />
            <KPICard label="Zuweisungen" value={stats.total_assignments} />
            <KPICard label="Abschlussrate" value={`${stats.completion_rate.toFixed(1)}%`} color={stats.completion_rate >= 80 ? 'green' : stats.completion_rate >= 50 ? 'yellow' : 'red'} />
            <KPICard label="Ueberfaellig" value={stats.overdue_count} color={stats.overdue_count > 0 ? 'red' : 'green'} />
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <KPICard label="Ausstehend" value={stats.pending_count} />
            <KPICard label="In Bearbeitung" value={stats.in_progress_count} />
            <KPICard label="Avg. Quiz-Score" value={`${stats.avg_quiz_score.toFixed(1)}%`} />
            <KPICard label="Deadlines (7d)" value={stats.upcoming_deadlines} color={stats.upcoming_deadlines > 5 ? 'yellow' : 'green'} />
          </div>

          {/* Status Bar */}
          <div className="bg-white border rounded-lg p-4">
            <h3 className="text-sm font-medium text-gray-700 mb-3">Status-Verteilung</h3>
            {stats.total_assignments > 0 && (
              <div className="flex gap-1 h-6 rounded-full overflow-hidden bg-gray-100">
                {stats.completed_count > 0 && <div className="bg-green-500" style={{ width: `${(stats.completed_count / stats.total_assignments) * 100}%` }} title={`Abgeschlossen: ${stats.completed_count}`} />}
                {stats.in_progress_count > 0 && <div className="bg-blue-500" style={{ width: `${(stats.in_progress_count / stats.total_assignments) * 100}%` }} title={`In Bearbeitung: ${stats.in_progress_count}`} />}
                {stats.pending_count > 0 && <div className="bg-gray-400" style={{ width: `${(stats.pending_count / stats.total_assignments) * 100}%` }} title={`Ausstehend: ${stats.pending_count}`} />}
                {stats.overdue_count > 0 && <div className="bg-red-500" style={{ width: `${(stats.overdue_count / stats.total_assignments) * 100}%` }} title={`Ueberfaellig: ${stats.overdue_count}`} />}
              </div>
            )}
            <div className="flex gap-4 mt-2 text-xs text-gray-500">
              <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-full bg-green-500 inline-block" /> Abgeschlossen</span>
              <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-full bg-blue-500 inline-block" /> In Bearbeitung</span>
              <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-full bg-gray-400 inline-block" /> Ausstehend</span>
              <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-full bg-red-500 inline-block" /> Ueberfaellig</span>
            </div>
          </div>

          {/* Deadlines */}
          {deadlines.length > 0 && (
            <div className="bg-white border rounded-lg p-4">
              <h3 className="text-sm font-medium text-gray-700 mb-3">Naechste Deadlines</h3>
              <div className="space-y-2">
                {deadlines.slice(0, 5).map(d => (
                  <div key={d.assignment_id} className="flex items-center justify-between text-sm">
                    <div>
                      <span className="font-medium">{d.module_title}</span>
                      <span className="text-gray-500 ml-2">({d.user_name})</span>
                    </div>
                    <span className={`px-2 py-0.5 rounded text-xs ${
                      d.days_left <= 0 ? 'bg-red-100 text-red-700' :
                      d.days_left <= 7 ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-600'
                    }`}>
                      {d.days_left <= 0 ? `${Math.abs(d.days_left)} Tage ueberfaellig` : `${d.days_left} Tage`}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {activeTab === 'modules' && (
        <div className="space-y-4">
          <div className="flex gap-3">
            <select value={regulationFilter} onChange={e => setRegulationFilter(e.target.value)} className="px-3 py-1.5 text-sm border rounded-lg bg-white">
              <option value="">Alle Bereiche</option>
              {Object.entries(REGULATION_LABELS).map(([key, label]) => (
                <option key={key} value={key}>{label}</option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredModules.map(m => (
              <div key={m.id} className="bg-white border rounded-lg p-4 hover:shadow-sm transition-shadow">
                <div className="flex items-start justify-between">
                  <div>
                    <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${REGULATION_COLORS[m.regulation_area]?.bg || 'bg-gray-100'} ${REGULATION_COLORS[m.regulation_area]?.text || 'text-gray-700'}`}>
                      {REGULATION_LABELS[m.regulation_area] || m.regulation_area}
                    </span>
                    <h3 className="mt-2 font-medium text-gray-900">{m.title}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">{m.module_code}</p>
                  </div>
                  {m.nis2_relevant && (
                    <span className="text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded">NIS2</span>
                  )}
                </div>
                {m.description && <p className="text-sm text-gray-600 mt-2 line-clamp-2">{m.description}</p>}
                <div className="flex items-center gap-3 mt-3 text-xs text-gray-500">
                  <span>{m.duration_minutes} Min.</span>
                  <span>{FREQUENCY_LABELS[m.frequency_type]}</span>
                  <span>Quiz: {m.pass_threshold}%</span>
                </div>
              </div>
            ))}
          </div>
          {filteredModules.length === 0 && <p className="text-center text-gray-500 py-8">Keine Module gefunden</p>}
        </div>
      )}

      {activeTab === 'matrix' && matrix && (
        <div className="space-y-4">
          <p className="text-sm text-gray-600">Compliance Training Matrix (CTM): Welche Rollen benoetigen welche Schulungsmodule</p>
          <div className="overflow-x-auto">
            <table className="w-full text-sm border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left p-2 border font-medium text-gray-700 w-48">Rolle</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Module</th>
                  <th className="text-center p-2 border font-medium text-gray-700 w-20">Anzahl</th>
                </tr>
              </thead>
              <tbody>
                {ALL_ROLES.map(role => {
                  const entries = matrix.entries[role] || []
                  return (
                    <tr key={role} className="border-b hover:bg-gray-50">
                      <td className="p-2 border font-medium">
                        <span className="text-gray-900">{role}</span>
                        <span className="text-gray-500 ml-1 text-xs">{ROLE_LABELS[role]}</span>
                      </td>
                      <td className="p-2 border">
                        <div className="flex flex-wrap gap-1">
                          {entries.map(e => (
                            <span key={e.id || e.module_id} className={`inline-block px-2 py-0.5 rounded text-xs ${e.is_mandatory ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`} title={`${e.module_title} (${e.is_mandatory ? 'Pflicht' : 'Optional'})`}>
                              {e.module_code}
                            </span>
                          ))}
                          {entries.length === 0 && <span className="text-gray-400 text-xs">Keine Module</span>}
                        </div>
                      </td>
                      <td className="p-2 border text-center">{entries.length}</td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeTab === 'assignments' && (
        <div className="space-y-4">
          <div className="flex gap-3">
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="px-3 py-1.5 text-sm border rounded-lg bg-white">
              <option value="">Alle Status</option>
              {Object.entries(STATUS_LABELS).map(([key, label]) => (
                <option key={key} value={key}>{label}</option>
              ))}
            </select>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-sm border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left p-2 border font-medium text-gray-700">Modul</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Mitarbeiter</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Rolle</th>
                  <th className="text-center p-2 border font-medium text-gray-700">Fortschritt</th>
                  <th className="text-center p-2 border font-medium text-gray-700">Status</th>
                  <th className="text-center p-2 border font-medium text-gray-700">Quiz</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Deadline</th>
                  <th className="text-center p-2 border font-medium text-gray-700">Eskalation</th>
                </tr>
              </thead>
              <tbody>
                {filteredAssignments.map(a => (
                  <tr key={a.id} className="border-b hover:bg-gray-50">
                    <td className="p-2 border">
                      <div className="font-medium">{a.module_title || a.module_code}</div>
                      <div className="text-xs text-gray-500">{a.module_code}</div>
                    </td>
                    <td className="p-2 border">
                      <div>{a.user_name}</div>
                      <div className="text-xs text-gray-500">{a.user_email}</div>
                    </td>
                    <td className="p-2 border text-xs">{a.role_code || '-'}</td>
                    <td className="p-2 border text-center">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 bg-gray-200 rounded-full h-2">
                          <div className="bg-blue-500 h-2 rounded-full" style={{ width: `${a.progress_percent}%` }} />
                        </div>
                        <span className="text-xs w-8">{a.progress_percent}%</span>
                      </div>
                    </td>
                    <td className="p-2 border text-center">
                      <span className={`px-2 py-0.5 rounded text-xs ${STATUS_COLORS[a.status]?.bg || ''} ${STATUS_COLORS[a.status]?.text || ''}`}>
                        {STATUS_LABELS[a.status] || a.status}
                      </span>
                    </td>
                    <td className="p-2 border text-center text-xs">
                      {a.quiz_score != null ? (
                        <span className={`font-medium ${a.quiz_passed ? 'text-green-600' : 'text-red-600'}`}>{a.quiz_score.toFixed(0)}%</span>
                      ) : '-'}
                    </td>
                    <td className="p-2 border text-xs">{new Date(a.deadline).toLocaleDateString('de-DE')}</td>
                    <td className="p-2 border text-center">
                      {a.escalation_level > 0 ? <span className="px-2 py-0.5 rounded text-xs bg-red-100 text-red-700">L{a.escalation_level}</span> : '-'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {filteredAssignments.length === 0 && <p className="text-center text-gray-500 py-8">Keine Zuweisungen</p>}
        </div>
      )}

      {activeTab === 'content' && (
        <div className="space-y-6">
          {/* Bulk Generation */}
          <div className="bg-white border rounded-lg p-4">
            <h3 className="text-sm font-medium text-gray-700 mb-3">Bulk-Generierung</h3>
            <p className="text-xs text-gray-500 mb-4">Generiere Inhalte und Quiz-Fragen fuer alle Module auf einmal</p>
            <div className="flex gap-3">
              <button
                onClick={handleBulkContent}
                disabled={bulkGenerating}
                className="px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
              >
                {bulkGenerating ? 'Generiere...' : 'Alle Inhalte generieren'}
              </button>
              <button
                onClick={handleBulkQuiz}
                disabled={bulkGenerating}
                className="px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
              >
                {bulkGenerating ? 'Generiere...' : 'Alle Quizfragen generieren'}
              </button>
            </div>
            {bulkResult && (
              <div className="mt-4 p-3 bg-gray-50 rounded-lg text-sm">
                <div className="flex gap-6">
                  <span className="text-green-700">Generiert: {bulkResult.generated}</span>
                  <span className="text-gray-500">Uebersprungen: {bulkResult.skipped}</span>
                  {bulkResult.errors?.length > 0 && (
                    <span className="text-red-600">Fehler: {bulkResult.errors.length}</span>
                  )}
                </div>
                {bulkResult.errors?.length > 0 && (
                  <div className="mt-2 text-xs text-red-600">
                    {bulkResult.errors.map((err, i) => <div key={i}>{err}</div>)}
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="bg-white border rounded-lg p-4">
            <h3 className="text-sm font-medium text-gray-700 mb-3">LLM-Content-Generator</h3>
            <p className="text-xs text-gray-500 mb-4">Generiere Schulungsinhalte und Quiz-Fragen automatisch via KI</p>
            <div className="flex gap-3 items-end">
              <div className="flex-1">
                <label className="text-xs text-gray-600 block mb-1">Modul auswaehlen</label>
                <select
                  value={selectedModuleId}
                  onChange={e => { setSelectedModuleId(e.target.value); setGeneratedContent(null); setModuleMedia([]); if (e.target.value) { handleLoadContent(e.target.value); loadModuleMedia(e.target.value); } }}
                  className="w-full px-3 py-2 text-sm border rounded-lg bg-white"
                >
                  <option value="">Modul waehlen...</option>
                  {modules.map(m => <option key={m.id} value={m.id}>{m.module_code} - {m.title}</option>)}
                </select>
              </div>
              <button onClick={handleGenerateContent} disabled={!selectedModuleId || generating} className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
                {generating ? 'Generiere...' : 'Inhalt generieren'}
              </button>
              <button onClick={handleGenerateQuiz} disabled={!selectedModuleId || generating} className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
                {generating ? 'Generiere...' : 'Quiz generieren'}
              </button>
            </div>
          </div>

          {generatedContent && (
            <div className="bg-white border rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <div>
                  <h3 className="text-sm font-medium text-gray-700">Generierter Inhalt (v{generatedContent.version})</h3>
                  <p className="text-xs text-gray-500">Generiert von: {generatedContent.generated_by} ({generatedContent.llm_model})</p>
                </div>
                {!generatedContent.is_published ? (
                  <button onClick={() => handlePublishContent(generatedContent.id)} className="px-3 py-1.5 text-xs bg-green-600 text-white rounded hover:bg-green-700">Veroeffentlichen</button>
                ) : (
                  <span className="px-3 py-1.5 text-xs bg-green-100 text-green-700 rounded">Veroeffentlicht</span>
                )}
              </div>
              <div className="prose prose-sm max-w-none border rounded p-4 bg-gray-50 max-h-96 overflow-y-auto">
                <pre className="whitespace-pre-wrap text-sm text-gray-800">{generatedContent.content_body}</pre>
              </div>
            </div>
          )}

          {/* Audio Player */}
          {selectedModuleId && generatedContent?.is_published && (
            <AudioPlayer
              moduleId={selectedModuleId}
              audio={moduleMedia.find(m => m.media_type === 'audio') || null}
              onMediaUpdate={() => loadModuleMedia(selectedModuleId)}
            />
          )}

          {/* Video Player */}
          {selectedModuleId && generatedContent?.is_published && (
            <VideoPlayer
              moduleId={selectedModuleId}
              video={moduleMedia.find(m => m.media_type === 'video') || null}
              onMediaUpdate={() => loadModuleMedia(selectedModuleId)}
            />
          )}

          {/* Script Preview */}
          {selectedModuleId && generatedContent?.is_published && (
            <ScriptPreview moduleId={selectedModuleId} />
          )}
        </div>
      )}

      {activeTab === 'audit' && (
        <div className="space-y-4">
          <div className="overflow-x-auto">
            <table className="w-full text-sm border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left p-2 border font-medium text-gray-700">Zeitpunkt</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Aktion</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Entitaet</th>
                  <th className="text-left p-2 border font-medium text-gray-700">Details</th>
                </tr>
              </thead>
              <tbody>
                {auditLog.map(entry => (
                  <tr key={entry.id} className="border-b hover:bg-gray-50">
                    <td className="p-2 border text-xs text-gray-600">{new Date(entry.created_at).toLocaleString('de-DE')}</td>
                    <td className="p-2 border"><span className="px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-700">{entry.action}</span></td>
                    <td className="p-2 border text-xs">{entry.entity_type}</td>
                    <td className="p-2 border text-xs text-gray-600">{JSON.stringify(entry.details).substring(0, 100)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {auditLog.length === 0 && <p className="text-center text-gray-500 py-8">Keine Audit-Eintraege</p>}
        </div>
      )}
    </div>
  )
}

function KPICard({ label, value, color }: { label: string; value: string | number; color?: string }) {
  const colorMap: Record<string, string> = {
    green: 'bg-green-50 border-green-200',
    yellow: 'bg-yellow-50 border-yellow-200',
    red: 'bg-red-50 border-red-200',
  }
  const textMap: Record<string, string> = {
    green: 'text-green-700',
    yellow: 'text-yellow-700',
    red: 'text-red-700',
  }
  return (
    <div className={`border rounded-lg p-4 ${color ? colorMap[color] || 'bg-white border-gray-200' : 'bg-white border-gray-200'}`}>
      <p className="text-xs text-gray-500">{label}</p>
      <p className={`text-2xl font-bold mt-1 ${color ? textMap[color] || 'text-gray-900' : 'text-gray-900'}`}>{value}</p>
    </div>
  )
}
