'use client'

import type { StepGroundTruthProps, ImageRegionWithState } from './ground-truth-types'
import { useGroundTruthSession } from './useGroundTruthSession'
import { ReconstructionPanel } from './ReconstructionPanel'
import { ImageRegionsPanel } from './ImageRegionsPanel'
import { ValidationPanel } from './ValidationPanel'

export function StepGroundTruth({ sessionId, onNext }: StepGroundTruthProps) {
  const s = useGroundTruthSession(sessionId)

  const handleUpdateRegion = (index: number, update: Partial<ImageRegionWithState>) => {
    s.setImageRegions(prev => prev.map((r, j) =>
      j === index ? { ...r, ...update } : r
    ))
  }

  if (s.status === 'loading') {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-500 mr-3" />
        <span className="text-gray-500 dark:text-gray-400">Session wird geladen...</span>
      </div>
    )
  }

  if (s.status === 'error' && !s.session) {
    return (
      <div className="text-center py-16">
        <p className="text-red-500">{s.error}</p>
        <button onClick={s.loadSessionData} className="mt-4 px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700">
          Erneut laden
        </button>
      </div>
    )
  }

  if (!s.session) return null

  const aspect = s.session.imageHeight / s.session.imageWidth

  return (
    <div className="space-y-4">
      {/* Header / Controls */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h3 className="text-lg font-medium text-gray-800 dark:text-gray-200">
          Validierung — Original vs. Rekonstruktion
        </h3>
        <div className="flex items-center gap-3">
          <button
            onClick={s.handleDetectImages}
            disabled={s.detecting}
            className="px-3 py-1.5 text-sm bg-indigo-600 text-white rounded hover:bg-indigo-700 disabled:opacity-50"
          >
            {s.detecting ? 'Erkennung laeuft...' : 'Bilder erkennen'}
          </button>
          <label className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">
            <input
              type="checkbox"
              checked={s.syncScroll}
              onChange={e => s.setSyncScroll(e.target.checked)}
              className="rounded"
            />
            Sync Scroll
          </label>
          <div className="flex items-center gap-1.5">
            <button onClick={() => s.setZoom(z => Math.max(50, z - 25))} className="px-2 py-1 text-sm border rounded dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">-</button>
            <span className="text-sm text-gray-600 dark:text-gray-400 w-12 text-center">{s.zoom}%</span>
            <button onClick={() => s.setZoom(z => Math.min(200, z + 25))} className="px-2 py-1 text-sm border rounded dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">+</button>
          </div>
        </div>
      </div>

      {s.error && (
        <div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-sm rounded">
          {s.error}
          <button onClick={() => s.setError('')} className="ml-2 underline">Schliessen</button>
        </div>
      )}

      {/* Side-by-side panels */}
      <div className="grid grid-cols-2 gap-4" style={{ height: 'calc(100vh - 580px)', minHeight: 300 }}>
        {/* Left: Original */}
        <div className="border rounded-lg dark:border-gray-700 overflow-hidden flex flex-col">
          <div className="px-3 py-1.5 bg-gray-50 dark:bg-gray-800 text-sm font-medium text-gray-600 dark:text-gray-400 border-b dark:border-gray-700">
            Original
          </div>
          <div
            ref={s.leftPanelRef}
            className="flex-1 overflow-auto"
            onScroll={() => s.handleScroll('left')}
          >
            <div style={{ width: `${s.zoom}%`, minWidth: '100%' }}>
              <img
                src={s.session.originalImageUrl}
                alt="Original"
                className="w-full h-auto"
                draggable={false}
              />
            </div>
          </div>
        </div>

        {/* Right: Reconstruction */}
        <ReconstructionPanel
          cells={s.session.cells}
          aspect={aspect}
          zoom={s.zoom}
          reconWidth={s.reconWidth}
          imageRegions={s.imageRegions}
          drawingRegion={s.drawingRegion}
          dragStart={s.dragStart}
          dragEnd={s.dragEnd}
          panelRef={s.rightPanelRef}
          reconRef={s.reconRef}
          onScroll={() => s.handleScroll('right')}
          onToggleDrawing={() => s.setDrawingRegion(!s.drawingRegion)}
          onMouseDown={s.handleReconMouseDown}
          onMouseMove={s.handleReconMouseMove}
          onMouseUp={s.handleReconMouseUp}
        />
      </div>

      {/* Image regions editor */}
      <ImageRegionsPanel
        imageRegions={s.imageRegions}
        onUpdateRegion={handleUpdateRegion}
        onGenerateImage={s.handleGenerateImage}
        onRemoveRegion={s.handleRemoveRegion}
      />

      {/* Notes, score, and action bar */}
      <ValidationPanel
        notes={s.notes}
        score={s.score}
        status={s.status}
        isGroundTruth={s.isGroundTruth}
        gtSaving={s.gtSaving}
        gtMessage={s.gtMessage}
        onNotesChange={s.setNotes}
        onScoreChange={s.setScore}
        onSave={s.handleSave}
        onMarkGroundTruth={s.handleMarkGroundTruth}
        onFinish={onNext}
      />
    </div>
  )
}
