'use client'

/**
 * Klausur Detail Page - Student List
 *
 * Shows all student works for a specific Klausur with upload capability.
 * Allows navigation to individual correction workspaces.
 */

import { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import AdminLayout from '@/components/admin/AdminLayout'
import Link from 'next/link'
import type { Klausur, StudentWork, STATUS_COLORS, STATUS_LABELS } from '../types'

const API_BASE = process.env.NEXT_PUBLIC_KLAUSUR_SERVICE_URL || 'http://localhost:8086'

// Status configuration
const statusConfig: Record<string, { color: string; label: string; bg: string }> = {
  UPLOADED: { color: 'text-gray-600', label: 'Hochgeladen', bg: 'bg-gray-100' },
  OCR_PROCESSING: { color: 'text-yellow-600', label: 'OCR läuft', bg: 'bg-yellow-100' },
  OCR_COMPLETE: { color: 'text-blue-600', label: 'OCR fertig', bg: 'bg-blue-100' },
  ANALYZING: { color: 'text-purple-600', label: 'Analyse', bg: 'bg-purple-100' },
  FIRST_EXAMINER: { color: 'text-orange-600', label: 'Erstkorrektur', bg: 'bg-orange-100' },
  SECOND_EXAMINER: { color: 'text-cyan-600', label: 'Zweitkorrektur', bg: 'bg-cyan-100' },
  COMPLETED: { color: 'text-green-600', label: 'Fertig', bg: 'bg-green-100' },
  ERROR: { color: 'text-red-600', label: 'Fehler', bg: 'bg-red-100' },
}

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

  const [klausur, setKlausur] = useState<Klausur | null>(null)
  const [students, setStudents] = useState<StudentWork[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [exporting, setExporting] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // Fetch Klausur details
  const fetchKlausur = useCallback(async () => {
    try {
      const res = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}`)
      if (res.ok) {
        const data = await res.json()
        setKlausur(data)
      } else if (res.status === 404) {
        setError('Klausur nicht gefunden')
      }
    } catch (err) {
      console.error('Failed to fetch klausur:', err)
      setError('Verbindung fehlgeschlagen')
    }
  }, [klausurId])

  // Fetch students
  const fetchStudents = useCallback(async () => {
    try {
      setLoading(true)
      const res = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}/students`)
      if (res.ok) {
        const data = await res.json()
        setStudents(Array.isArray(data) ? data : data.students || [])
        setError(null)
      }
    } catch (err) {
      console.error('Failed to fetch students:', err)
      setError('Fehler beim Laden der Arbeiten')
    } finally {
      setLoading(false)
    }
  }, [klausurId])

  useEffect(() => {
    fetchKlausur()
    fetchStudents()
  }, [fetchKlausur, fetchStudents])

  // PDF Export functions
  const exportOverviewPDF = async () => {
    try {
      setExporting(true)
      const res = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}/export/overview`)
      if (res.ok) {
        const blob = await res.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `Notenuebersicht_${klausur?.title?.replace(/\s+/g, '_') || 'Klausur'}_${new Date().toISOString().split('T')[0]}.pdf`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      } else {
        setError('Fehler beim PDF-Export')
      }
    } catch (err) {
      console.error('Failed to export overview PDF:', err)
      setError('Fehler beim PDF-Export')
    } finally {
      setExporting(false)
    }
  }

  const exportAllGutachtenPDF = async () => {
    try {
      setExporting(true)
      const res = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}/export/all-gutachten`)
      if (res.ok) {
        const blob = await res.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `Alle_Gutachten_${klausur?.title?.replace(/\s+/g, '_') || 'Klausur'}_${new Date().toISOString().split('T')[0]}.pdf`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      } else {
        setError('Fehler beim PDF-Export')
      }
    } catch (err) {
      console.error('Failed to export all gutachten PDF:', err)
      setError('Fehler beim PDF-Export')
    } finally {
      setExporting(false)
    }
  }

  // Handle file upload
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files || files.length === 0) return

    setUploading(true)
    setUploadProgress(0)
    setError(null)

    const totalFiles = files.length
    let uploadedCount = 0

    for (const file of Array.from(files)) {
      try {
        const formData = new FormData()
        formData.append('file', file)

        const res = await fetch(`${API_BASE}/api/v1/klausuren/${klausurId}/students`, {
          method: 'POST',
          body: formData,
        })

        if (!res.ok) {
          const errorData = await res.json()
          console.error(`Failed to upload ${file.name}:`, errorData)
        }

        uploadedCount++
        setUploadProgress(Math.round((uploadedCount / totalFiles) * 100))
      } catch (err) {
        console.error(`Failed to upload ${file.name}:`, err)
      }
    }

    setUploading(false)
    setUploadProgress(0)
    fetchStudents()

    // Reset file input
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // Handle delete student work
  const handleDeleteStudent = async (studentId: string) => {
    if (!confirm('Studentenarbeit wirklich löschen?')) return

    try {
      const res = await fetch(`${API_BASE}/api/v1/students/${studentId}`, {
        method: 'DELETE',
      })

      if (res.ok) {
        setStudents(prev => prev.filter(s => s.id !== studentId))
      } else {
        setError('Fehler beim Löschen')
      }
    } catch (err) {
      console.error('Failed to delete student:', err)
      setError('Fehler beim Löschen')
    }
  }

  // Get grade display
  const getGradeDisplay = (student: StudentWork) => {
    if (student.grade_points === undefined || student.grade_points === null) {
      return { points: '-', label: '-' }
    }
    const 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'
    }
    return {
      points: student.grade_points.toString(),
      label: labels[student.grade_points] || '-'
    }
  }

  // Calculate statistics
  const stats = {
    total: students.length,
    completed: students.filter(s => s.status === 'COMPLETED').length,
    inProgress: students.filter(s => ['FIRST_EXAMINER', 'SECOND_EXAMINER', 'ANALYZING'].includes(s.status)).length,
    pending: students.filter(s => ['UPLOADED', 'OCR_PROCESSING', 'OCR_COMPLETE'].includes(s.status)).length,
    avgGrade: students.filter(s => s.grade_points !== undefined && s.grade_points !== null)
      .reduce((sum, s, _, arr) => sum + (s.grade_points || 0) / arr.length, 0).toFixed(1),
  }

  if (loading && !klausur) {
    return (
      <AdminLayout title="Lädt..." description="">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout
      title={klausur?.title || 'Klausur'}
      description={`${klausur?.subject} - ${klausur?.year} | ${students.length} Arbeiten`}
    >
      {/* Breadcrumb */}
      <div className="mb-4">
        <Link
          href="/lehrer/klausur-korrektur"
          className="text-primary-600 hover:text-primary-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>
          Zurück zur Übersicht
        </Link>
      </div>

      {/* Error display */}
      {error && (
        <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center gap-3">
          <svg className="w-5 h-5 text-red-600" 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 className="text-red-800">{error}</span>
          <button onClick={() => setError(null)} className="ml-auto text-red-600 hover:text-red-800">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
      )}

      {/* Statistics Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
        <div className="bg-white rounded-lg border border-slate-200 p-4">
          <div className="text-2xl font-bold text-slate-800">{stats.total}</div>
          <div className="text-sm text-slate-500">Gesamt</div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-4">
          <div className="text-2xl font-bold text-green-600">{stats.completed}</div>
          <div className="text-sm text-slate-500">Fertig</div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-4">
          <div className="text-2xl font-bold text-orange-600">{stats.inProgress}</div>
          <div className="text-sm text-slate-500">In Arbeit</div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-4">
          <div className="text-2xl font-bold text-gray-600">{stats.pending}</div>
          <div className="text-sm text-slate-500">Ausstehend</div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-4">
          <div className="text-2xl font-bold text-primary-600">{stats.avgGrade}</div>
          <div className="text-sm text-slate-500">Ø Note</div>
        </div>
      </div>

      {/* Fairness Analysis Button */}
      {stats.completed >= 2 && (
        <div className="mb-6 flex flex-wrap gap-3">
          <Link
            href={`/lehrer/klausur-korrektur/${klausurId}/fairness`}
            className="inline-flex items-center gap-2 px-4 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:from-purple-700 hover:to-indigo-700 transition-all shadow-sm"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
            Fairness-Analyse oeffnen
            <span className="text-xs bg-white/20 px-2 py-0.5 rounded-full">
              {stats.completed} bewertet
            </span>
          </Link>

          {/* PDF Export Buttons */}
          <button
            onClick={exportOverviewPDF}
            disabled={exporting}
            className="inline-flex items-center gap-2 px-4 py-3 bg-white border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-all shadow-sm disabled:opacity-50"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
            {exporting ? 'Exportiere...' : 'Notenuebersicht PDF'}
          </button>

          <button
            onClick={exportAllGutachtenPDF}
            disabled={exporting}
            className="inline-flex items-center gap-2 px-4 py-3 bg-white border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-all shadow-sm disabled:opacity-50"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
            {exporting ? 'Exportiere...' : 'Alle Gutachten PDF'}
          </button>
        </div>
      )}

      {/* Upload Section */}
      <div className="bg-white rounded-lg border border-slate-200 p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-slate-800">Studentenarbeiten hochladen</h2>
            <p className="text-sm text-slate-500">PDF oder Bilder (JPG, PNG) der gescannten Arbeiten</p>
          </div>
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept=".pdf,.jpg,.jpeg,.png"
            onChange={handleFileUpload}
            className="hidden"
            id="file-upload"
          />
          <label
            htmlFor="file-upload"
            className={`px-4 py-2 rounded-lg flex items-center gap-2 cursor-pointer ${
              uploading
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                : 'bg-primary-600 text-white hover:bg-primary-700'
            }`}
          >
            {uploading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                {uploadProgress}%
              </>
            ) : (
              <>
                <svg className="w-5 h-5" 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-8l-4-4m0 0L8 8m4-4v12" />
                </svg>
                Dateien hochladen
              </>
            )}
          </label>
        </div>

        {/* Upload progress */}
        {uploading && (
          <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
            <div
              className="h-full bg-primary-600 rounded-full transition-all"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        )}
      </div>

      {/* Students List */}
      <div className="bg-white rounded-lg border border-slate-200 overflow-hidden">
        <div className="p-4 border-b border-slate-200">
          <h2 className="text-lg font-semibold text-slate-800">Studentenarbeiten ({students.length})</h2>
        </div>

        {loading ? (
          <div className="flex items-center justify-center h-32">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600"></div>
          </div>
        ) : students.length === 0 ? (
          <div className="p-8 text-center text-slate-500">
            <svg className="mx-auto h-12 w-12 text-slate-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>Noch keine Arbeiten hochgeladen</p>
            <p className="text-sm">Laden Sie gescannte PDFs oder Bilder hoch</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-200">
            {students.map((student, index) => {
              const grade = getGradeDisplay(student)
              const status = statusConfig[student.status] || statusConfig.UPLOADED

              return (
                <div
                  key={student.id}
                  className="p-4 hover:bg-slate-50 flex items-center gap-4"
                >
                  {/* Index */}
                  <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-sm font-medium text-slate-600">
                    {index + 1}
                  </div>

                  {/* Student info */}
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-slate-800 truncate">
                      {student.anonym_id || `Arbeit ${index + 1}`}
                    </div>
                    <div className="text-sm text-slate-500 flex items-center gap-2">
                      <span className={`px-2 py-0.5 rounded-full text-xs ${status.bg} ${status.color}`}>
                        {status.label}
                      </span>
                    </div>
                  </div>

                  {/* Grade */}
                  <div className="text-center w-20">
                    <div className="text-lg font-bold text-slate-800">{grade.points}</div>
                    <div className="text-xs text-slate-500">{grade.label}</div>
                  </div>

                  {/* Progress indicator */}
                  <div className="w-24">
                    {student.criteria_scores && Object.keys(student.criteria_scores).length > 0 ? (
                      <div className="flex gap-1">
                        {['rechtschreibung', 'grammatik', 'inhalt', 'struktur', 'stil'].map(criterion => (
                          <div
                            key={criterion}
                            className={`h-2 flex-1 rounded-full ${
                              student.criteria_scores[criterion] !== undefined
                                ? 'bg-green-500'
                                : 'bg-slate-200'
                            }`}
                            title={criterion}
                          />
                        ))}
                      </div>
                    ) : (
                      <div className="text-xs text-slate-400">Keine Bewertung</div>
                    )}
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2">
                    <Link
                      href={`/lehrer/klausur-korrektur/${klausurId}/${student.id}`}
                      className="px-3 py-1.5 bg-primary-600 text-white text-sm rounded-lg hover:bg-primary-700"
                    >
                      Korrigieren
                    </Link>
                    <button
                      onClick={() => handleDeleteStudent(student.id)}
                      className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg"
                      title="Löschen"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* Fairness Check Button */}
      {students.filter(s => s.status === 'COMPLETED').length >= 3 && (
        <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-semibold text-blue-800">Fairness-Check verfügbar</h3>
              <p className="text-sm text-blue-600">
                Prüfen Sie die Bewertungen auf Konsistenz und Fairness
              </p>
            </div>
            <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
              Fairness-Check starten
            </button>
          </div>
        </div>
      )}
    </AdminLayout>
  )
}
