'use client'

/**
 * Right panel (1/3 width): Tabs for Kriterien, Annotationen, Gutachten, EH-Vorschlaege.
 */

import { AnnotationPanel, EHSuggestionPanel } from '../../../components'
import type {
  Klausur,
  Annotation,
  AnnotationType,
  GradeInfo,
  CriteriaScores,
} from '../../../types'
import type { ExaminerWorkflow, ActiveTab, GradeTotals } from './workspace-types'
import { API_BASE } from './workspace-types'
import { CriteriaTab } from './CriteriaTab'

interface CorrectionPanelProps {
  // Data
  klausur: Klausur | null
  klausurId: string
  studentId: string
  annotations: Annotation[]
  gradeInfo: GradeInfo | null
  criteriaScores: CriteriaScores
  gutachten: string
  workflow: ExaminerWorkflow | null
  totals: GradeTotals
  selectedAnnotation: Annotation | null

  // UI flags
  activeTab: ActiveTab
  generatingGutachten: boolean
  saving: boolean
  exporting: boolean
  submittingWorkflow: boolean

  // Actions
  onSetActiveTab: (tab: ActiveTab) => void
  onCriteriaChange: (criterion: string, value: number) => void
  onSelectTool: (tool: AnnotationType) => void
  onSelectAnnotation: (ann: Annotation | null) => void
  onUpdateAnnotation: (id: string, updates: Partial<Annotation>) => Promise<void>
  onDeleteAnnotation: (id: string) => Promise<void>
  onSetGutachten: (text: string | ((prev: string) => string)) => void
  onGenerateGutachten: () => Promise<void>
  onSaveGutachten: () => Promise<void>
  onExportGutachtenPDF: () => Promise<void>
  onSubmitErstkorrektur: () => Promise<void>
  onStartZweitkorrektur: (zkId: string) => Promise<void>
  onSubmitZweitkorrektur: () => Promise<void>
  onOpenEinigung: () => void
}

export function CorrectionPanel({
  klausur,
  klausurId,
  studentId,
  annotations,
  gradeInfo,
  criteriaScores,
  gutachten,
  workflow,
  totals,
  selectedAnnotation,
  activeTab,
  generatingGutachten,
  saving,
  exporting,
  submittingWorkflow,
  onSetActiveTab,
  onCriteriaChange,
  onSelectTool,
  onSelectAnnotation,
  onUpdateAnnotation,
  onDeleteAnnotation,
  onSetGutachten,
  onGenerateGutachten,
  onSaveGutachten,
  onExportGutachtenPDF,
  onSubmitErstkorrektur,
  onStartZweitkorrektur,
  onSubmitZweitkorrektur,
  onOpenEinigung,
}: CorrectionPanelProps) {
  return (
    <div className="w-1/3 bg-white rounded-lg border border-slate-200 overflow-hidden flex flex-col">
      {/* Tabs */}
      <div className="border-b border-slate-200">
        <nav className="flex">
          {[
            { id: 'kriterien' as const, label: 'Kriterien' },
            { id: 'annotationen' as const, label: `Notizen (${annotations.length})` },
            { id: 'gutachten' as const, label: 'Gutachten' },
            { id: 'eh-vorschlaege' as const, label: 'EH' },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => onSetActiveTab(tab.id)}
              className={`flex-1 px-2 py-3 text-xs font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-primary-500 text-primary-600'
                  : 'border-transparent text-slate-500 hover:text-slate-700'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab content */}
      <div className="flex-1 overflow-auto p-4">
        {/* Kriterien Tab */}
        {activeTab === 'kriterien' && gradeInfo && (
          <CriteriaTab
            gradeInfo={gradeInfo}
            criteriaScores={criteriaScores}
            annotations={annotations}
            totals={totals}
            workflow={workflow}
            generatingGutachten={generatingGutachten}
            submittingWorkflow={submittingWorkflow}
            gutachten={gutachten}
            onCriteriaChange={onCriteriaChange}
            onSelectTool={onSelectTool}
            onGenerateGutachten={onGenerateGutachten}
            onSubmitErstkorrektur={onSubmitErstkorrektur}
            onStartZweitkorrektur={onStartZweitkorrektur}
            onSubmitZweitkorrektur={onSubmitZweitkorrektur}
            onOpenEinigung={onOpenEinigung}
          />
        )}

        {/* Annotationen Tab */}
        {activeTab === 'annotationen' && (
          <div className="h-full -m-4">
            <AnnotationPanel
              annotations={annotations}
              selectedAnnotation={selectedAnnotation}
              onSelectAnnotation={onSelectAnnotation}
              onUpdateAnnotation={onUpdateAnnotation}
              onDeleteAnnotation={onDeleteAnnotation}
            />
          </div>
        )}

        {/* Gutachten Tab */}
        {activeTab === 'gutachten' && (
          <GutachtenTab
            gutachten={gutachten}
            generatingGutachten={generatingGutachten}
            saving={saving}
            exporting={exporting}
            onSetGutachten={onSetGutachten}
            onGenerateGutachten={onGenerateGutachten}
            onSaveGutachten={onSaveGutachten}
            onExportGutachtenPDF={onExportGutachtenPDF}
          />
        )}

        {/* EH-Vorschlaege Tab */}
        {activeTab === 'eh-vorschlaege' && (
          <div className="h-full -m-4">
            <EHSuggestionPanel
              studentId={studentId}
              klausurId={klausurId}
              hasEH={!!klausur?.eh_id || true}
              apiBase={API_BASE}
              onInsertSuggestion={(text, criterion) => {
                onSetGutachten((prev: string) =>
                  prev
                    ? `${prev}\n\n[${criterion.toUpperCase()}]: ${text}`
                    : `[${criterion.toUpperCase()}]: ${text}`,
                )
                onSetActiveTab('gutachten')
              }}
            />
          </div>
        )}
      </div>
    </div>
  )
}

// ---- Gutachten sub-component ----

interface GutachtenTabProps {
  gutachten: string
  generatingGutachten: boolean
  saving: boolean
  exporting: boolean
  onSetGutachten: (text: string | ((prev: string) => string)) => void
  onGenerateGutachten: () => void
  onSaveGutachten: () => void
  onExportGutachtenPDF: () => void
}

function GutachtenTab({
  gutachten,
  generatingGutachten,
  saving,
  exporting,
  onSetGutachten,
  onGenerateGutachten,
  onSaveGutachten,
  onExportGutachtenPDF,
}: GutachtenTabProps) {
  return (
    <div className="h-full flex flex-col">
      <textarea
        value={gutachten}
        onChange={(e) => onSetGutachten(e.target.value)}
        placeholder="Gutachten hier eingeben oder generieren lassen..."
        className="flex-1 w-full p-3 border border-slate-300 rounded-lg resize-none focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm"
      />
      <div className="flex gap-2 mt-4">
        <button
          onClick={onGenerateGutachten}
          disabled={generatingGutachten}
          className="flex-1 py-2 border border-primary-600 text-primary-600 rounded-lg hover:bg-primary-50 disabled:opacity-50"
        >
          {generatingGutachten ? 'Generiere...' : 'Neu generieren'}
        </button>
        <button
          onClick={onSaveGutachten}
          disabled={saving}
          className="flex-1 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50"
        >
          {saving ? 'Speichern...' : 'Speichern'}
        </button>
      </div>

      {/* PDF Export */}
      {gutachten && (
        <div className="flex gap-2 mt-2 pt-2 border-t border-slate-200">
          <button
            onClick={onExportGutachtenPDF}
            disabled={exporting}
            className="flex-1 py-2 border border-slate-300 text-slate-600 rounded-lg hover:bg-slate-50 disabled:opacity-50 flex items-center justify-center gap-2 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="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...' : 'Als PDF exportieren'}
          </button>
        </div>
      )}
    </div>
  )
}
