'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { useTheme } from '@/lib/ThemeContext'
import { Sidebar } from '@/components/Sidebar'
import { ThemeToggle } from '@/components/ThemeToggle'
import { LanguageDropdown } from '@/components/LanguageDropdown'
import { korrekturApi } from '@/lib/korrektur/api'
import type { Klausur, StudentWork, FairnessAnalysis } from '../../types'
import { DEFAULT_CRITERIA, ANNOTATION_COLORS, getGradeLabel } from '../../types'

// =============================================================================
// GLASS CARD
// =============================================================================

interface GlassCardProps {
  children: React.ReactNode
  className?: string
  delay?: number
  isDark?: boolean
}

function GlassCard({ children, className = '', delay = 0, isDark = true }: GlassCardProps) {
  const [isVisible, setIsVisible] = useState(false)

  useEffect(() => {
    const timer = setTimeout(() => setIsVisible(true), delay)
    return () => clearTimeout(timer)
  }, [delay])

  return (
    <div
      className={`rounded-3xl p-5 ${className}`}
      style={{
        background: isDark ? 'rgba(255, 255, 255, 0.08)' : 'rgba(255, 255, 255, 0.7)',
        backdropFilter: 'blur(24px) saturate(180%)',
        WebkitBackdropFilter: 'blur(24px) saturate(180%)',
        border: isDark ? '1px solid rgba(255, 255, 255, 0.1)' : '1px solid rgba(0, 0, 0, 0.1)',
        boxShadow: isDark
          ? '0 4px 24px rgba(0, 0, 0, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.05)'
          : '0 4px 24px rgba(0, 0, 0, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.5)',
        opacity: isVisible ? 1 : 0,
        transform: isVisible ? 'translateY(0)' : 'translateY(20px)',
        transition: 'all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)',
      }}
    >
      {children}
    </div>
  )
}

// =============================================================================
// HISTOGRAM
// =============================================================================

interface HistogramProps {
  students: StudentWork[]
  className?: string
  isDark?: boolean
}

function Histogram({ students, className = '', isDark = true }: HistogramProps) {
  // Group students by grade points (0-15)
  const distribution = useMemo(() => {
    const counts: Record<number, number> = {}
    for (let i = 0; i <= 15; i++) {
      counts[i] = 0
    }
    for (const student of students) {
      if (student.grade_points !== undefined) {
        counts[student.grade_points] = (counts[student.grade_points] || 0) + 1
      }
    }
    return counts
  }, [students])

  const maxCount = Math.max(...Object.values(distribution), 1)

  return (
    <div className={className}>
      <h3 className={`font-semibold mb-4 ${isDark ? 'text-white' : 'text-slate-900'}`}>Notenverteilung</h3>
      <div className="flex items-end gap-1 h-40">
        {Array.from({ length: 16 }, (_, i) => 15 - i).map((grade) => {
          const count = distribution[grade] || 0
          const height = (count / maxCount) * 100

          // Color based on grade
          let color = '#22c55e' // Green for good grades
          if (grade <= 4) color = '#ef4444' // Red for poor grades
          else if (grade <= 9) color = '#f97316' // Orange for medium grades

          return (
            <div
              key={grade}
              className="flex-1 flex flex-col items-center gap-1"
            >
              <span className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>{count || ''}</span>
              <div
                className="w-full rounded-t transition-all hover:opacity-80"
                style={{
                  height: `${height}%`,
                  minHeight: count > 0 ? '8px' : '0',
                  backgroundColor: color,
                }}
                title={`${grade} Punkte (${getGradeLabel(grade)}): ${count} Schueler`}
              />
              <span className={`text-xs ${isDark ? 'text-white/50' : 'text-slate-500'}`}>{grade}</span>
            </div>
          )
        })}
      </div>
      <p className={`text-xs text-center mt-2 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>Punkte</p>
    </div>
  )
}

// =============================================================================
// CRITERIA HEATMAP
// =============================================================================

interface CriteriaHeatmapProps {
  students: StudentWork[]
  className?: string
  isDark?: boolean
}

function CriteriaHeatmap({ students, className = '', isDark = true }: CriteriaHeatmapProps) {
  // Calculate average for each criterion
  const criteriaAverages = useMemo(() => {
    const sums: Record<string, { sum: number; count: number }> = {}

    for (const criterion of Object.keys(DEFAULT_CRITERIA)) {
      sums[criterion] = { sum: 0, count: 0 }
    }

    for (const student of students) {
      if (student.criteria_scores) {
        for (const [criterion, score] of Object.entries(student.criteria_scores)) {
          if (score !== undefined && sums[criterion]) {
            sums[criterion].sum += score
            sums[criterion].count += 1
          }
        }
      }
    }

    const averages: Record<string, number> = {}
    for (const [criterion, data] of Object.entries(sums)) {
      averages[criterion] = data.count > 0 ? Math.round(data.sum / data.count) : 0
    }

    return averages
  }, [students])

  return (
    <div className={className}>
      <h3 className={`font-semibold mb-4 ${isDark ? 'text-white' : 'text-slate-900'}`}>Kriterien-Durchschnitt</h3>
      <div className="space-y-3">
        {Object.entries(DEFAULT_CRITERIA).map(([criterion, config]) => {
          const average = criteriaAverages[criterion] || 0
          const color = ANNOTATION_COLORS[criterion as keyof typeof ANNOTATION_COLORS] || '#6b7280'

          return (
            <div key={criterion} className="space-y-1">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: color }}
                  />
                  <span className={`text-sm ${isDark ? 'text-white/70' : 'text-slate-600'}`}>{config.name}</span>
                </div>
                <span className={`text-sm font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>{average}%</span>
              </div>
              <div className={`h-2 rounded-full overflow-hidden ${isDark ? 'bg-white/10' : 'bg-slate-200'}`}>
                <div
                  className="h-full rounded-full transition-all"
                  style={{
                    width: `${average}%`,
                    backgroundColor: color,
                  }}
                />
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// =============================================================================
// OUTLIER LIST
// =============================================================================

interface OutlierListProps {
  fairness: FairnessAnalysis | null
  onStudentClick: (studentId: string) => void
  className?: string
  isDark?: boolean
}

function OutlierList({ fairness, onStudentClick, className = '', isDark = true }: OutlierListProps) {
  if (!fairness || fairness.outliers.length === 0) {
    return (
      <div className={`text-center py-8 ${className}`}>
        <div className="w-12 h-12 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-3">
          <svg className="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <p className={`text-sm ${isDark ? 'text-white/60' : 'text-slate-600'}`}>Keine Ausreisser erkannt</p>
        <p className={`text-xs mt-1 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>Alle Bewertungen sind konsistent</p>
      </div>
    )
  }

  return (
    <div className={className}>
      <h3 className={`font-semibold mb-4 ${isDark ? 'text-white' : 'text-slate-900'}`}>
        Ausreisser ({fairness.outliers.length})
      </h3>
      <div className="space-y-2 max-h-64 overflow-y-auto">
        {fairness.outliers.map((outlier) => (
          <button
            key={outlier.student_id}
            onClick={() => onStudentClick(outlier.student_id)}
            className={`w-full p-3 rounded-xl border transition-colors text-left ${isDark ? 'bg-white/5 border-white/10 hover:bg-white/10' : 'bg-slate-100 border-slate-200 hover:bg-slate-200'}`}
          >
            <div className="flex items-center justify-between mb-1">
              <span className={`font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>{outlier.anonym_id}</span>
              <span
                className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                  outlier.deviation > 0
                    ? 'bg-green-500/20 text-green-400'
                    : 'bg-red-500/20 text-red-400'
                }`}
              >
                {outlier.deviation > 0 ? '+' : ''}{outlier.deviation.toFixed(1)} Punkte
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span className={`text-sm ${isDark ? 'text-white/50' : 'text-slate-500'}`}>
                {outlier.grade_points} Punkte ({getGradeLabel(outlier.grade_points)})
              </span>
              <span className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>{outlier.reason}</span>
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}

// =============================================================================
// FAIRNESS SCORE
// =============================================================================

interface FairnessScoreProps {
  fairness: FairnessAnalysis | null
  className?: string
  isDark?: boolean
}

function FairnessScore({ fairness, className = '', isDark = true }: FairnessScoreProps) {
  const score = fairness?.fairness_score || 0
  const percentage = Math.round(score * 100)

  let color = '#22c55e' // Green
  let label = 'Ausgezeichnet'
  if (percentage < 70) {
    color = '#ef4444'
    label = 'Ueberpruefung empfohlen'
  } else if (percentage < 85) {
    color = '#f97316'
    label = 'Akzeptabel'
  } else if (percentage < 95) {
    color = '#22c55e'
    label = 'Gut'
  }

  // SVG ring
  const size = 120
  const strokeWidth = 10
  const radius = (size - strokeWidth) / 2
  const circumference = radius * 2 * Math.PI
  const offset = circumference - (percentage / 100) * circumference

  return (
    <div className={`text-center ${className}`}>
      <div className="relative inline-block" style={{ width: size, height: size }}>
        <svg className="transform -rotate-90" width={size} height={size}>
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            fill="none"
            stroke={isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'}
            strokeWidth={strokeWidth}
          />
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            fill="none"
            stroke={color}
            strokeWidth={strokeWidth}
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            strokeLinecap="round"
            style={{ transition: 'stroke-dashoffset 1s ease-out' }}
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className={`text-3xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>{percentage}</span>
          <span className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>%</span>
        </div>
      </div>
      <p className={`font-medium mt-3 ${isDark ? 'text-white' : 'text-slate-900'}`}>{label}</p>
      <p className={`text-xs mt-1 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>Fairness-Score</p>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function FairnessPage() {
  const { isDark } = useTheme()
  const router = useRouter()
  const params = useParams()
  const klausurId = params.klausurId as string

  // State
  const [klausur, setKlausur] = useState<Klausur | null>(null)
  const [students, setStudents] = useState<StudentWork[]>([])
  const [fairness, setFairness] = useState<FairnessAnalysis | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Load data
  const loadData = useCallback(async () => {
    if (!klausurId) return

    setIsLoading(true)
    setError(null)

    try {
      const [klausurData, studentsData, fairnessData] = await Promise.all([
        korrekturApi.getKlausur(klausurId),
        korrekturApi.getStudents(klausurId),
        korrekturApi.getFairnessAnalysis(klausurId),
      ])

      setKlausur(klausurData)
      setStudents(studentsData)
      setFairness(fairnessData)
    } catch (err) {
      console.error('Failed to load data:', err)
      setError(err instanceof Error ? err.message : 'Laden fehlgeschlagen')
    } finally {
      setIsLoading(false)
    }
  }, [klausurId])

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

  // Calculated stats
  const stats = useMemo(() => {
    if (!fairness) return null

    return {
      studentCount: fairness.student_count,
      average: fairness.average_grade,
      stdDev: fairness.std_deviation,
      spread: fairness.spread,
      outlierCount: fairness.outliers.length,
      warningCount: fairness.warnings.length,
    }
  }, [fairness])

  return (
    <div className={`min-h-screen flex relative overflow-hidden ${
      isDark
        ? 'bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800'
        : 'bg-gradient-to-br from-slate-100 via-blue-50 to-indigo-100'
    }`}>
      {/* Animated Background Blobs */}
      <div className={`absolute -top-40 -right-40 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob ${isDark ? 'bg-purple-500 opacity-30' : 'bg-purple-300 opacity-40'}`} />
      <div className={`absolute top-1/2 -left-40 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-2000 ${isDark ? 'bg-pink-500 opacity-30' : 'bg-pink-300 opacity-40'}`} />
      <div className={`absolute -bottom-40 right-1/3 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-4000 ${isDark ? 'bg-blue-500 opacity-30' : 'bg-blue-300 opacity-40'}`} />

      {/* Sidebar */}
      <div className="relative z-10 p-4">
        <Sidebar />
      </div>

      {/* Main Content */}
      <div className="flex-1 flex flex-col relative z-10 p-6 overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <button
              onClick={() => router.push(`/korrektur/${klausurId}`)}
              className={`p-2 rounded-xl transition-colors ${isDark ? 'bg-white/10 hover:bg-white/20 text-white' : 'bg-slate-200 hover:bg-slate-300 text-slate-700'}`}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
            </button>
            <div>
              <h1 className={`text-3xl font-bold mb-1 ${isDark ? 'text-white' : 'text-slate-900'}`}>Fairness-Analyse</h1>
              <p className={isDark ? 'text-white/50' : 'text-slate-500'}>{klausur?.title}</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <a
              href={korrekturApi.getOverviewExportUrl(klausurId)}
              target="_blank"
              rel="noopener noreferrer"
              className={`px-4 py-2 rounded-xl transition-colors flex items-center gap-2 ${isDark ? 'bg-white/10 text-white hover:bg-white/20' : 'bg-slate-200 text-slate-700 hover:bg-slate-300'}`}
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              PDF Export
            </a>
            <ThemeToggle />
            <LanguageDropdown />
          </div>
        </div>

        {/* Error Display */}
        {error && (
          <GlassCard className="mb-6" isDark={isDark}>
            <div className="flex items-center gap-3 text-red-400">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>{error}</span>
              <button
                onClick={loadData}
                className={`ml-auto px-3 py-1 rounded-lg transition-colors text-sm ${isDark ? 'bg-white/10 hover:bg-white/20' : 'bg-slate-200 hover:bg-slate-300'}`}
              >
                Erneut versuchen
              </button>
            </div>
          </GlassCard>
        )}

        {/* Loading */}
        {isLoading && (
          <div className="flex-1 flex items-center justify-center">
            <div className="w-12 h-12 border-4 border-purple-500 border-t-transparent rounded-full animate-spin" />
          </div>
        )}

        {/* Content */}
        {!isLoading && fairness && (
          <>
            {/* Stats Row */}
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6">
              <GlassCard delay={100} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Arbeiten</p>
                <p className={`text-2xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>{stats?.studentCount}</p>
              </GlassCard>
              <GlassCard delay={150} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Durchschnitt</p>
                <p className={`text-2xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>
                  {stats?.average.toFixed(1)} P
                </p>
              </GlassCard>
              <GlassCard delay={200} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Standardabw.</p>
                <p className={`text-2xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>
                  {stats?.stdDev.toFixed(2)}
                </p>
              </GlassCard>
              <GlassCard delay={250} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Spannweite</p>
                <p className={`text-2xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>{stats?.spread} P</p>
              </GlassCard>
              <GlassCard delay={300} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Ausreisser</p>
                <p className={`text-2xl font-bold ${stats?.outlierCount ? 'text-amber-400' : 'text-green-400'}`}>
                  {stats?.outlierCount}
                </p>
              </GlassCard>
              <GlassCard delay={350} isDark={isDark}>
                <p className={`text-xs mb-1 ${isDark ? 'text-white/50' : 'text-slate-500'}`}>Warnungen</p>
                <p className={`text-2xl font-bold ${stats?.warningCount ? 'text-red-400' : 'text-green-400'}`}>
                  {stats?.warningCount}
                </p>
              </GlassCard>
            </div>

            {/* Warnings */}
            {fairness.warnings.length > 0 && (
              <GlassCard className="mb-6" delay={400} isDark={isDark}>
                <h3 className={`font-semibold mb-3 flex items-center gap-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>
                  <svg className="w-5 h-5 text-amber-400" 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>
                  Warnungen
                </h3>
                <ul className="space-y-2">
                  {fairness.warnings.map((warning, index) => (
                    <li key={index} className={`text-sm flex items-start gap-2 ${isDark ? 'text-white/70' : 'text-slate-600'}`}>
                      <span className="text-amber-400 mt-1">-</span>
                      {warning}
                    </li>
                  ))}
                </ul>
              </GlassCard>
            )}

            {/* Main Grid */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* Fairness Score */}
              <GlassCard delay={450} isDark={isDark}>
                <FairnessScore fairness={fairness} isDark={isDark} />
              </GlassCard>

              {/* Histogram */}
              <GlassCard className="lg:col-span-2" delay={500} isDark={isDark}>
                <Histogram students={students} isDark={isDark} />
              </GlassCard>

              {/* Criteria Heatmap */}
              <GlassCard delay={550} isDark={isDark}>
                <CriteriaHeatmap students={students} isDark={isDark} />
              </GlassCard>

              {/* Outlier List */}
              <GlassCard className="lg:col-span-2" delay={600} isDark={isDark}>
                <OutlierList
                  fairness={fairness}
                  onStudentClick={(studentId) =>
                    router.push(`/korrektur/${klausurId}/${studentId}`)
                  }
                  isDark={isDark}
                />
              </GlassCard>
            </div>
          </>
        )}

        {/* No Data */}
        {!isLoading && !fairness && !error && (
          <GlassCard className="text-center py-12" isDark={isDark}>
            <div className={`w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4 ${isDark ? 'bg-white/10' : 'bg-slate-200'}`}>
              <svg className={`w-8 h-8 ${isDark ? 'text-white/30' : 'text-slate-400'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
            </div>
            <h3 className={`text-xl font-semibold mb-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>Keine Daten verfuegbar</h3>
            <p className={isDark ? 'text-white/50' : 'text-slate-500'}>
              Die Fairness-Analyse erfordert korrigierte Arbeiten.
            </p>
          </GlassCard>
        )}
      </div>
    </div>
  )
}
