'use client'

/**
 * Kriterien tab content: scoring sliders, annotation counts per criterion,
 * totals summary, and workflow action buttons.
 */

import type { Annotation, AnnotationType, GradeInfo, CriteriaScores } from '../../../types'
import { ANNOTATION_COLORS } from '../../../types'
import type { ExaminerWorkflow, GradeTotals } from './workspace-types'
import { GRADE_LABELS } from './workspace-types'

interface CriteriaTabProps {
  gradeInfo: GradeInfo
  criteriaScores: CriteriaScores
  annotations: Annotation[]
  totals: GradeTotals
  workflow: ExaminerWorkflow | null
  generatingGutachten: boolean
  submittingWorkflow: boolean
  gutachten: string
  onCriteriaChange: (criterion: string, value: number) => void
  onSelectTool: (tool: AnnotationType) => void
  onGenerateGutachten: () => void
  onSubmitErstkorrektur: () => void
  onStartZweitkorrektur: (zkId: string) => void
  onSubmitZweitkorrektur: () => void
  onOpenEinigung: () => void
}

export function CriteriaTab({
  gradeInfo,
  criteriaScores,
  annotations,
  totals,
  workflow,
  generatingGutachten,
  submittingWorkflow,
  gutachten,
  onCriteriaChange,
  onSelectTool,
  onGenerateGutachten,
  onSubmitErstkorrektur,
  onStartZweitkorrektur,
  onSubmitZweitkorrektur,
  onOpenEinigung,
}: CriteriaTabProps) {
  return (
    <div className="space-y-4">
      {Object.entries(gradeInfo.criteria || {}).map(([key, criterion]) => {
        const score = criteriaScores[key] || 0
        const linkedAnnotations = annotations.filter(
          (a) => a.linked_criterion === key || a.type === key,
        )
        const errorCount = linkedAnnotations.length
        const severityCounts = {
          minor: linkedAnnotations.filter((a) => a.severity === 'minor').length,
          major: linkedAnnotations.filter((a) => a.severity === 'major').length,
          critical: linkedAnnotations.filter((a) => a.severity === 'critical').length,
        }
        const criterionColor = ANNOTATION_COLORS[key as AnnotationType] || '#6b7280'

        return (
          <div key={key} className="bg-slate-50 rounded-lg p-4">
            <div className="flex justify-between items-center mb-2">
              <div className="flex items-center gap-2">
                <div
                  className="w-3 h-3 rounded-full"
                  style={{ backgroundColor: criterionColor }}
                />
                <span className="font-medium text-slate-800">{criterion.name}</span>
                <span className="text-xs text-slate-500">({criterion.weight}%)</span>
              </div>
              <div className="text-lg font-bold text-slate-800">{score}%</div>
            </div>

            {/* Annotation count for this criterion */}
            {errorCount > 0 && (
              <div className="flex items-center gap-2 mb-2 text-xs">
                <span className="text-slate-500">{errorCount} Markierungen:</span>
                {severityCounts.minor > 0 && (
                  <span className="px-1.5 py-0.5 bg-yellow-100 text-yellow-700 rounded">
                    {severityCounts.minor} leicht
                  </span>
                )}
                {severityCounts.major > 0 && (
                  <span className="px-1.5 py-0.5 bg-orange-100 text-orange-700 rounded">
                    {severityCounts.major} mittel
                  </span>
                )}
                {severityCounts.critical > 0 && (
                  <span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded">
                    {severityCounts.critical} schwer
                  </span>
                )}
              </div>
            )}

            {/* Slider */}
            <input
              type="range"
              min="0"
              max="100"
              value={score}
              onChange={(e) => onCriteriaChange(key, parseInt(e.target.value))}
              className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer"
              style={{ accentColor: criterionColor }}
            />

            {/* Quick buttons */}
            <div className="flex gap-1 mt-2">
              {[0, 25, 50, 75, 100].map((val) => (
                <button
                  key={val}
                  onClick={() => onCriteriaChange(key, val)}
                  className={`flex-1 py-1 text-xs rounded transition-colors ${
                    score === val
                      ? 'text-white'
                      : 'bg-slate-200 text-slate-600 hover:bg-slate-300'
                  }`}
                  style={score === val ? { backgroundColor: criterionColor } : undefined}
                >
                  {val}%
                </button>
              ))}
            </div>

            {/* Quick add annotation button for RS/Grammatik */}
            {(key === 'rechtschreibung' || key === 'grammatik') && (
              <button
                onClick={() => onSelectTool(key as AnnotationType)}
                className="mt-2 w-full py-1 text-xs border rounded hover:bg-slate-100 flex items-center justify-center gap-1"
                style={{ borderColor: criterionColor, color: criterionColor }}
              >
                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                {key === 'rechtschreibung' ? 'RS-Fehler' : 'Grammatik-Fehler'} markieren
              </button>
            )}
          </div>
        )
      })}

      {/* Total and action buttons */}
      <CriteriaTotals
        totals={totals}
        workflow={workflow}
        generatingGutachten={generatingGutachten}
        submittingWorkflow={submittingWorkflow}
        gutachten={gutachten}
        onGenerateGutachten={onGenerateGutachten}
        onSubmitErstkorrektur={onSubmitErstkorrektur}
        onStartZweitkorrektur={onStartZweitkorrektur}
        onSubmitZweitkorrektur={onSubmitZweitkorrektur}
        onOpenEinigung={onOpenEinigung}
      />
    </div>
  )
}

// ---- Sub-component: totals + workflow buttons ----

interface CriteriaTotalsProps {
  totals: GradeTotals
  workflow: ExaminerWorkflow | null
  generatingGutachten: boolean
  submittingWorkflow: boolean
  gutachten: string
  onGenerateGutachten: () => void
  onSubmitErstkorrektur: () => void
  onStartZweitkorrektur: (zkId: string) => void
  onSubmitZweitkorrektur: () => void
  onOpenEinigung: () => void
}

function CriteriaTotals({
  totals,
  workflow,
  generatingGutachten,
  submittingWorkflow,
  gutachten,
  onGenerateGutachten,
  onSubmitErstkorrektur,
  onStartZweitkorrektur,
  onSubmitZweitkorrektur,
  onOpenEinigung,
}: CriteriaTotalsProps) {
  return (
    <div className="border-t border-slate-200 pt-4 mt-4">
      <div className="flex justify-between items-center mb-4">
        <span className="font-semibold text-slate-800">Gesamtergebnis</span>
        <div className="text-right">
          <div className="text-2xl font-bold text-primary-600">
            {totals.gradePoints} Punkte
          </div>
          <div className="text-sm text-slate-500">
            ({totals.weighted}%) - Note {GRADE_LABELS[totals.gradePoints]}
          </div>
        </div>
      </div>

      <div className="space-y-2">
        {/* Generate Gutachten */}
        <button
          onClick={onGenerateGutachten}
          disabled={generatingGutachten}
          className="w-full py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 disabled:opacity-50 flex items-center justify-center gap-2 text-sm"
        >
          {generatingGutachten ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-slate-700"></div>
              Generiere Gutachten...
            </>
          ) : (
            <>
              <svg className="w-4 h-4" 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>
              Gutachten generieren
            </>
          )}
        </button>

        {/* Workflow buttons */}
        <WorkflowButtons
          workflow={workflow}
          submittingWorkflow={submittingWorkflow}
          gutachten={gutachten}
          totals={totals}
          onSubmitErstkorrektur={onSubmitErstkorrektur}
          onStartZweitkorrektur={onStartZweitkorrektur}
          onSubmitZweitkorrektur={onSubmitZweitkorrektur}
          onOpenEinigung={onOpenEinigung}
        />
      </div>
    </div>
  )
}

// ---- Sub-component: workflow action buttons ----

interface WorkflowButtonsProps {
  workflow: ExaminerWorkflow | null
  submittingWorkflow: boolean
  gutachten: string
  totals: GradeTotals
  onSubmitErstkorrektur: () => void
  onStartZweitkorrektur: (zkId: string) => void
  onSubmitZweitkorrektur: () => void
  onOpenEinigung: () => void
}

function WorkflowButtons({
  workflow,
  submittingWorkflow,
  gutachten,
  totals,
  onSubmitErstkorrektur,
  onStartZweitkorrektur,
  onSubmitZweitkorrektur,
  onOpenEinigung,
}: WorkflowButtonsProps) {
  return (
    <>
      {/* EK submit */}
      {(!workflow || workflow.workflow_status === 'not_started' || workflow.workflow_status === 'ek_in_progress') && (
        <button
          onClick={onSubmitErstkorrektur}
          disabled={submittingWorkflow || !gutachten}
          className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2"
        >
          {submittingWorkflow ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              Wird abgeschlossen...
            </>
          ) : (
            <>
              <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>
              Erstkorrektur abschliessen
            </>
          )}
        </button>
      )}

      {/* Forward to ZK */}
      {workflow?.workflow_status === 'ek_completed' && workflow.user_role === 'ek' && (
        <button
          onClick={() => {
            const zkId = prompt('Zweitkorrektor-ID eingeben:')
            if (zkId) onStartZweitkorrektur(zkId)
          }}
          disabled={submittingWorkflow}
          className="w-full py-3 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 flex items-center justify-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
          </svg>
          Zur Zweitkorrektur weiterleiten
        </button>
      )}

      {/* ZK submit */}
      {(workflow?.workflow_status === 'zk_assigned' || workflow?.workflow_status === 'zk_in_progress') &&
        workflow?.user_role === 'zk' && (
          <button
            onClick={onSubmitZweitkorrektur}
            disabled={submittingWorkflow || !gutachten}
            className="w-full py-3 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 flex items-center justify-center gap-2"
          >
            {submittingWorkflow ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                Wird abgeschlossen...
              </>
            ) : (
              <>
                <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>
                Zweitkorrektur abschliessen
              </>
            )}
          </button>
        )}

      {/* Einigung */}
      {workflow?.workflow_status === 'einigung_required' && (
        <button
          onClick={onOpenEinigung}
          className="w-full py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 flex items-center justify-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
          </svg>
          Einigung starten
        </button>
      )}

      {/* Completed */}
      {workflow?.workflow_status === 'completed' && (
        <div className="bg-green-100 text-green-800 p-4 rounded-lg text-center">
          <div className="text-2xl font-bold">
            Endnote: {workflow.final_grade} Punkte
          </div>
          <div className="text-sm mt-1">
            ({GRADE_LABELS[workflow.final_grade || 0]}) -{' '}
            {workflow.consensus_type === 'auto'
              ? 'Auto-Konsens'
              : workflow.consensus_type === 'drittkorrektur'
                ? 'Drittkorrektur'
                : 'Einigung'}
          </div>
        </div>
      )}

      {/* EK/ZK comparison */}
      {workflow?.first_result && workflow?.second_result && workflow?.workflow_status !== 'completed' && (
        <div className="bg-slate-50 rounded-lg p-3 mt-2">
          <div className="text-xs text-slate-500 mb-2">Notenvergleich</div>
          <div className="flex justify-between">
            <div className="text-center">
              <div className="text-sm text-slate-500">EK</div>
              <div className="font-bold text-blue-600">{workflow.first_result.grade_points}P</div>
            </div>
            <div className="text-center">
              <div className="text-sm text-slate-500">ZK</div>
              <div className="font-bold text-amber-600">{workflow.second_result.grade_points}P</div>
            </div>
            <div className="text-center">
              <div className="text-sm text-slate-500">Diff</div>
              <div className={`font-bold ${(workflow.grade_difference || 0) >= 4 ? 'text-red-600' : 'text-slate-700'}`}>
                {workflow.grade_difference}P
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
