'use client'

import { useState } from 'react'
import { PagePurpose } from '@/components/common/PagePurpose'
import { PipelineStepper } from '@/components/ocr-pipeline/PipelineStepper'
import { StepDeskew } from '@/components/ocr-pipeline/StepDeskew'
import { StepColumnDetection } from '@/components/ocr-pipeline/StepColumnDetection'
import { StepWordRecognition } from '@/components/ocr-pipeline/StepWordRecognition'
import { StepCoordinates } from '@/components/ocr-pipeline/StepCoordinates'
import { StepReconstruction } from '@/components/ocr-pipeline/StepReconstruction'
import { StepGroundTruth } from '@/components/ocr-pipeline/StepGroundTruth'
import { PIPELINE_STEPS, type PipelineStep } from './types'

export default function OcrPipelinePage() {
  const [currentStep, setCurrentStep] = useState(0)
  const [steps, setSteps] = useState<PipelineStep[]>(
    PIPELINE_STEPS.map((s, i) => ({
      ...s,
      status: i === 0 ? 'active' : 'pending',
    })),
  )

  const handleStepClick = (index: number) => {
    if (index <= currentStep || steps[index].status === 'completed') {
      setCurrentStep(index)
    }
  }

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setSteps((prev) =>
        prev.map((s, i) => {
          if (i === currentStep) return { ...s, status: 'completed' }
          if (i === currentStep + 1) return { ...s, status: 'active' }
          return s
        }),
      )
      setCurrentStep((prev) => prev + 1)
    }
  }

  const renderStep = () => {
    switch (currentStep) {
      case 0:
        return <StepDeskew onNext={handleNext} />
      case 1:
        return <StepColumnDetection />
      case 2:
        return <StepWordRecognition />
      case 3:
        return <StepCoordinates />
      case 4:
        return <StepReconstruction />
      case 5:
        return <StepGroundTruth />
      default:
        return null
    }
  }

  return (
    <div className="space-y-6">
      <PagePurpose
        title="OCR Pipeline"
        purpose="Schrittweise Seitenrekonstruktion: Scan begradigen, Spalten erkennen, Woerter lokalisieren und die Seite Wort fuer Wort nachbauen. Ziel: 10 Vokabelseiten fehlerfrei rekonstruieren."
        audience={['Entwickler', 'Data Scientists']}
        architecture={{
          services: ['klausur-service (FastAPI)', 'OpenCV', 'Tesseract'],
          databases: ['In-Memory Sessions'],
        }}
        relatedPages={[
          { name: 'OCR Vergleich', href: '/ai/ocr-compare', description: 'Methoden-Vergleich' },
          { name: 'OCR-Labeling', href: '/ai/ocr-labeling', description: 'Trainingsdaten' },
        ]}
        defaultCollapsed
      />

      <PipelineStepper steps={steps} currentStep={currentStep} onStepClick={handleStepClick} />

      <div className="min-h-[400px]">{renderStep()}</div>
    </div>
  )
}
