'use client'

/**
 * Fairness-Dashboard
 *
 * Visualizes grading consistency and identifies outliers for review.
 */

import { useState, useEffect, useCallback } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'

// Same-origin proxy to avoid CORS issues
const API_BASE = '/klausur-api'

const GRADE_LABELS: Record<number, string> = {
  15: '1+', 14: '1', 13: '1-', 12: '2+', 11: '2', 10: '2-',
  9: '3+', 8: '3', 7: '3-', 6: '4+', 5: '4', 4: '4-',
  3: '5+', 2: '5', 1: '5-', 0: '6'
}

const CRITERION_COLORS: Record<string, string> = {
  rechtschreibung: '#dc2626',
  grammatik: '#2563eb',
  inhalt: '#16a34a',
  struktur: '#9333ea',
  stil: '#ea580c',
}

interface FairnessData {
  klausur_id: string
  students_count: number
  graded_count: number
  statistics: {
    average_grade: number
    average_raw_points: number
    min_grade: number
    max_grade: number
    spread: number
    standard_deviation: number
  }
  criteria_breakdown: Record<string, {
    average: number
    min: number
    max: number
    count: number
  }>
  outliers: Array<{
    student_id: string
    student_name: string
    grade_points: number
    deviation: number
    direction: 'above' | 'below'
  }>
  fairness_score: number
  warnings: string[]
  recommendation: string
}

interface Klausur {
  id: string
  title: string
  subject: string
  students: Array<{
    id: string
    student_name: string
    anonym_id: string
    grade_points: number
    criteria_scores: Record<string, { score: number }>
  }>
}

export default function FairnessDashboardPage() {
  const params = useParams()
  const router = useRouter()
  const klausurId = params.klausurId as string

  const [klausur, setKlausur] = useState<Klausur | null>(null)
  const [fairnessData, setFairnessData] = useState<FairnessData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchData = useCallback(async () => {
    try {
      setLoading(true)

      const klausurRes = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}`)
      if (klausurRes.ok) {
        setKlausur(await klausurRes.json())
      }

      const fairnessRes = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}/fairness`)
      if (fairnessRes.ok) {
        setFairnessData(await fairnessRes.json())
      } else {
        const errData = await fairnessRes.json()
        setError(errData.detail || 'Fehler beim Laden der Fairness-Analyse')
      }

      setError(null)
    } catch (err) {
      console.error('Failed to fetch data:', err)
      setError('Fehler beim Laden der Daten')
    } finally {
      setLoading(false)
    }
  }, [klausurId])

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

  const getGradeDistribution = () => {
    if (!klausur?.students) return []

    const distribution: Record<number, number> = {}
    for (let i = 0; i <= 15; i++) {
      distribution[i] = 0
    }

    klausur.students.forEach(s => {
      if (s.grade_points >= 0 && s.grade_points <= 15) {
        distribution[s.grade_points]++
      }
    })

    return Object.entries(distribution).map(([grade, count]) => ({
      grade: parseInt(grade),
      count,
      label: GRADE_LABELS[parseInt(grade)] || grade
    }))
  }

  const gradeDistribution = getGradeDistribution()
  const maxCount = Math.max(...gradeDistribution.map(d => d.count), 1)

  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-slate-50">
      <div className="max-w-7xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="bg-white border-b border-slate-200 -mx-4 -mt-6 px-4 py-4 mb-6">
          <div className="flex items-center justify-between">
            <Link
              href={`/education/klausur-korrektur/${klausurId}`}
              className="text-purple-600 hover:text-purple-800 flex items-center gap-1 text-sm"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              Zurueck zur Klausur
            </Link>

            <div className="text-sm text-slate-500">
              {fairnessData?.graded_count || 0} von {fairnessData?.students_count || 0} Arbeiten bewertet
            </div>
          </div>
        </div>

        {/* Page header */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-slate-800">Fairness-Analyse</h1>
          <p className="text-sm text-slate-500">{klausur?.title || ''}</p>
        </div>

        {/* Error display */}
        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
            {error}
          </div>
        )}

        {fairnessData && (
          <div className="space-y-6">
            {/* Top Row: Fairness Score + Statistics */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {/* Fairness Score Gauge */}
              <div className="bg-white rounded-lg border border-slate-200 p-6">
                <h3 className="text-sm font-medium text-slate-500 mb-4">Fairness-Score</h3>
                <div className="flex items-center justify-center">
                  <div className="relative w-32 h-32">
                    <svg className="w-32 h-32 transform -rotate-90">
                      <circle
                        cx="64"
                        cy="64"
                        r="56"
                        fill="none"
                        stroke="#e2e8f0"
                        strokeWidth="12"
                      />
                      <circle
                        cx="64"
                        cy="64"
                        r="56"
                        fill="none"
                        stroke={
                          fairnessData.fairness_score >= 70 ? '#16a34a' :
                          fairnessData.fairness_score >= 40 ? '#eab308' : '#dc2626'
                        }
                        strokeWidth="12"
                        strokeLinecap="round"
                        strokeDasharray={`${(fairnessData.fairness_score / 100) * 352} 352`}
                      />
                    </svg>
                    <div className="absolute inset-0 flex flex-col items-center justify-center">
                      <span className="text-3xl font-bold">{fairnessData.fairness_score}</span>
                      <span className="text-xs text-slate-500">von 100</span>
                    </div>
                  </div>
                </div>
                <div className={`mt-4 text-center text-sm font-medium ${
                  fairnessData.fairness_score >= 70 ? 'text-green-600' :
                  fairnessData.fairness_score >= 40 ? 'text-yellow-600' : 'text-red-600'
                }`}>
                  {fairnessData.recommendation}
                </div>
              </div>

              {/* Statistics */}
              <div className="bg-white rounded-lg border border-slate-200 p-6">
                <h3 className="text-sm font-medium text-slate-500 mb-4">Statistik</h3>
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-slate-600">Durchschnitt</span>
                    <span className="font-semibold">
                      {fairnessData.statistics.average_grade} P ({GRADE_LABELS[Math.round(fairnessData.statistics.average_grade)]})
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-600">Minimum</span>
                    <span className="font-semibold">
                      {fairnessData.statistics.min_grade} P ({GRADE_LABELS[fairnessData.statistics.min_grade]})
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-600">Maximum</span>
                    <span className="font-semibold">
                      {fairnessData.statistics.max_grade} P ({GRADE_LABELS[fairnessData.statistics.max_grade]})
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-600">Spreizung</span>
                    <span className="font-semibold">{fairnessData.statistics.spread} P</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-600">Standardabweichung</span>
                    <span className="font-semibold">{fairnessData.statistics.standard_deviation}</span>
                  </div>
                </div>
              </div>

              {/* Warnings */}
              <div className="bg-white rounded-lg border border-slate-200 p-6">
                <h3 className="text-sm font-medium text-slate-500 mb-4">Hinweise</h3>
                {fairnessData.warnings.length > 0 ? (
                  <div className="space-y-2">
                    {fairnessData.warnings.map((warning, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm">
                        <svg className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                        <span className="text-slate-700">{warning}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex items-center gap-2 text-green-600">
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                    <span className="text-sm">Keine Auffaelligkeiten erkannt</span>
                  </div>
                )}
              </div>
            </div>

            {/* Grade Distribution Histogram */}
            <div className="bg-white rounded-lg border border-slate-200 p-6">
              <h3 className="text-sm font-medium text-slate-500 mb-4">Notenverteilung</h3>
              <div className="flex items-end gap-1 h-48">
                {gradeDistribution.map(({ grade, count, label }) => (
                  <div key={grade} className="flex-1 flex flex-col items-center">
                    <div
                      className={`w-full rounded-t transition-all ${
                        count > 0 ? 'bg-purple-500' : 'bg-slate-200'
                      }`}
                      style={{ height: `${(count / maxCount) * 160}px`, minHeight: count > 0 ? '8px' : '2px' }}
                      title={`${count} Arbeiten`}
                    />
                    <div className="text-xs text-slate-500 mt-1 transform -rotate-45 origin-top-left w-6 text-center">
                      {label}
                    </div>
                    {count > 0 && (
                      <div className="text-xs font-medium text-slate-700 mt-1">{count}</div>
                    )}
                  </div>
                ))}
              </div>
              <div className="flex justify-between text-xs text-slate-400 mt-6">
                <span>6 (0 Punkte)</span>
                <span>1+ (15 Punkte)</span>
              </div>
            </div>

            {/* Criteria Breakdown Heatmap */}
            <div className="bg-white rounded-lg border border-slate-200 p-6">
              <h3 className="text-sm font-medium text-slate-500 mb-4">Kriterien-Vergleich</h3>
              <div className="space-y-3">
                {Object.entries(fairnessData.criteria_breakdown).map(([criterion, data]) => {
                  const color = CRITERION_COLORS[criterion] || '#6b7280'
                  const range = data.max - data.min

                  return (
                    <div key={criterion} className="flex items-center gap-4">
                      <div className="w-32 flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: color }} />
                        <span className="text-sm font-medium capitalize">{criterion}</span>
                      </div>
                      <div className="flex-1">
                        <div className="relative h-6 bg-slate-100 rounded-full overflow-hidden">
                          <div
                            className="absolute h-full opacity-30"
                            style={{
                              backgroundColor: color,
                              left: `${data.min}%`,
                              width: `${range}%`
                            }}
                          />
                          <div
                            className="absolute top-0 bottom-0 w-1 rounded"
                            style={{
                              backgroundColor: color,
                              left: `${data.average}%`
                            }}
                          />
                        </div>
                      </div>
                      <div className="w-24 text-right">
                        <span className="text-sm font-semibold">{data.average}%</span>
                        <span className="text-xs text-slate-400 ml-1">avg</span>
                      </div>
                      <div className="w-20 text-right text-xs text-slate-500">
                        {data.min}% - {data.max}%
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>

            {/* Outliers List */}
            {fairnessData.outliers.length > 0 && (
              <div className="bg-white rounded-lg border border-slate-200 p-6">
                <h3 className="text-sm font-medium text-slate-500 mb-4">
                  Ausreisser ({fairnessData.outliers.length})
                </h3>
                <div className="space-y-2">
                  {fairnessData.outliers.map((outlier) => (
                    <div
                      key={outlier.student_id}
                      className={`flex items-center justify-between p-3 rounded-lg border ${
                        outlier.direction === 'above'
                          ? 'bg-green-50 border-green-200'
                          : 'bg-red-50 border-red-200'
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center text-white font-bold ${
                          outlier.direction === 'above' ? 'bg-green-500' : 'bg-red-500'
                        }`}>
                          {outlier.direction === 'above' ? '↑' : '↓'}
                        </div>
                        <div>
                          <div className="font-medium">{outlier.student_name}</div>
                          <div className="text-sm text-slate-500">
                            {outlier.grade_points} Punkte ({GRADE_LABELS[outlier.grade_points]}) -
                            Abweichung: {outlier.deviation} Punkte {outlier.direction === 'above' ? 'ueber' : 'unter'} Durchschnitt
                          </div>
                        </div>
                      </div>
                      <Link
                        href={`/education/klausur-korrektur/${klausurId}/${outlier.student_id}`}
                        className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm hover:bg-slate-50 flex items-center gap-2"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                        Pruefen
                      </Link>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* All Students Table */}
            <div className="bg-white rounded-lg border border-slate-200 p-6">
              <h3 className="text-sm font-medium text-slate-500 mb-4">
                Alle Arbeiten ({klausur?.students.length || 0})
              </h3>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-slate-200">
                      <th className="text-left py-2 px-3 font-medium text-slate-600">Student</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">Note</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">RS</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">Gram</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">Inhalt</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">Struktur</th>
                      <th className="text-center py-2 px-3 font-medium text-slate-600">Stil</th>
                      <th className="text-right py-2 px-3 font-medium text-slate-600">Aktion</th>
                    </tr>
                  </thead>
                  <tbody>
                    {klausur?.students
                      .sort((a, b) => b.grade_points - a.grade_points)
                      .map((student) => {
                        const isOutlier = fairnessData.outliers.some(o => o.student_id === student.id)
                        const outlierInfo = fairnessData.outliers.find(o => o.student_id === student.id)

                        return (
                          <tr
                            key={student.id}
                            className={`border-b border-slate-100 ${
                              isOutlier
                                ? outlierInfo?.direction === 'above'
                                  ? 'bg-green-50'
                                  : 'bg-red-50'
                                : ''
                            }`}
                          >
                            <td className="py-2 px-3">
                              <div className="font-medium">{student.anonym_id}</div>
                            </td>
                            <td className="py-2 px-3 text-center">
                              <span className="font-bold">
                                {student.grade_points} ({GRADE_LABELS[student.grade_points] || '-'})
                              </span>
                            </td>
                            <td className="py-2 px-3 text-center">
                              {student.criteria_scores?.rechtschreibung?.score ?? '-'}%
                            </td>
                            <td className="py-2 px-3 text-center">
                              {student.criteria_scores?.grammatik?.score ?? '-'}%
                            </td>
                            <td className="py-2 px-3 text-center">
                              {student.criteria_scores?.inhalt?.score ?? '-'}%
                            </td>
                            <td className="py-2 px-3 text-center">
                              {student.criteria_scores?.struktur?.score ?? '-'}%
                            </td>
                            <td className="py-2 px-3 text-center">
                              {student.criteria_scores?.stil?.score ?? '-'}%
                            </td>
                            <td className="py-2 px-3 text-right">
                              <Link
                                href={`/education/klausur-korrektur/${klausurId}/${student.id}`}
                                className="text-purple-600 hover:text-purple-800 text-sm"
                              >
                                Bearbeiten
                              </Link>
                            </td>
                          </tr>
                        )
                      })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
