'use client'

/**
 * StepAnsicht — Split-view page layout comparison.
 *
 * Left:  Original scan with OCR word overlay (red) + coordinate grid
 * Right: Reconstructed layout with all zones + coordinate grid
 *
 * Both sides share the same coordinate system for easy visual comparison.
 */

import { useEffect, useRef, useState } from 'react'
import { useGridEditor } from '@/components/grid-editor/useGridEditor'
import type { GridZone, GridEditorCell } from '@/components/grid-editor/types'

const KLAUSUR_API = '/klausur-api'

interface StepAnsichtProps {
  sessionId: string | null
  onNext: () => void
}

function getCellColor(cell: GridEditorCell | undefined): string | null {
  if (!cell) return null
  if (cell.color_override) return cell.color_override
  const colored = cell.word_boxes?.find((wb) => wb.color_name && wb.color_name !== 'black')
  return colored?.color ?? null
}

export function StepAnsicht({ sessionId, onNext }: StepAnsichtProps) {
  const { grid, loading, error, loadGrid } = useGridEditor(sessionId)

  const leftRef = useRef<HTMLDivElement>(null)
  const [panelWidth, setPanelWidth] = useState(0)
  const [showGrid, setShowGrid] = useState(true)
  const [gridSpacing, setGridSpacing] = useState(100) // px in original coordinates

  useEffect(() => {
    if (sessionId) loadGrid()
  }, [sessionId]) // eslint-disable-line react-hooks/exhaustive-deps

  // Track panel width
  useEffect(() => {
    if (!leftRef.current) return
    const ro = new ResizeObserver(([entry]) => setPanelWidth(entry.contentRect.width))
    ro.observe(leftRef.current)
    return () => ro.disconnect()
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="w-8 h-8 border-4 border-teal-500 border-t-transparent rounded-full animate-spin" />
        <span className="ml-3 text-gray-500">Lade Vorschau...</span>
      </div>
    )
  }

  if (error || !grid) {
    return (
      <div className="p-8 text-center">
        <p className="text-red-500 mb-4">{error || 'Keine Grid-Daten.'}</p>
        <button onClick={onNext} className="px-5 py-2 bg-teal-600 text-white rounded-lg">Weiter →</button>
      </div>
    )
  }

  const imgW = grid.image_width || 1
  const imgH = grid.image_height || 1
  const scale = panelWidth > 0 ? panelWidth / imgW : 0.5
  const panelHeight = imgH * scale

  const baseFontPx = (grid as any).layout_metrics?.font_size_suggestion_px || 14
  const scaledFont = Math.max(7, baseFontPx * scale * 0.85)

  // Collect all word boxes for OCR overlay
  const allWordBoxes = grid.zones.flatMap((z) =>
    z.cells.flatMap((c) => (c.word_boxes || []).map((wb) => ({ ...wb, zone: z })))
  )

  return (
    <div className="space-y-3">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            Ansicht — Original vs. Rekonstruktion
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Links: Original mit OCR-Overlay. Rechts: Rekonstruierte Seite. Koordinatengitter zum Abgleich.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <label className="flex items-center gap-1.5 text-xs text-gray-500">
            <input
              type="checkbox"
              checked={showGrid}
              onChange={(e) => setShowGrid(e.target.checked)}
              className="w-3.5 h-3.5 rounded border-gray-300"
            />
            Gitter
          </label>
          <select
            value={gridSpacing}
            onChange={(e) => setGridSpacing(Number(e.target.value))}
            className="text-xs px-1.5 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700"
          >
            <option value={50}>50px</option>
            <option value={100}>100px</option>
            <option value={200}>200px</option>
          </select>
          <button onClick={onNext} className="px-5 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm font-medium">
            Weiter →
          </button>
        </div>
      </div>

      {/* Split view */}
      <div className="flex gap-2" style={{ height: panelHeight > 0 ? `${panelHeight + 40}px` : '600px' }}>
        {/* LEFT: Original + OCR overlay */}
        <div ref={leftRef} className="flex-1 relative border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-900">
          <div className="absolute top-0 left-0 px-2 py-0.5 bg-black/60 text-white text-[10px] font-medium rounded-br z-20">
            Original + OCR
          </div>

          {/* Scan image */}
          {sessionId && (
            <img
              src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`}
              alt="Original"
              className="absolute inset-0 w-full h-auto"
              style={{ height: `${panelHeight}px`, objectFit: 'contain' }}
            />
          )}

          {/* OCR word overlay (red text) */}
          {allWordBoxes.map((wb, i) => (
            <div
              key={i}
              className="absolute text-red-500 font-mono leading-none pointer-events-none"
              style={{
                left: `${wb.left * scale}px`,
                top: `${wb.top * scale}px`,
                fontSize: `${Math.max(6, wb.height * scale * 0.75)}px`,
                whiteSpace: 'nowrap',
              }}
            >
              {wb.text}
            </div>
          ))}

          {/* Coordinate grid */}
          {showGrid && <CoordinateGrid imgW={imgW} imgH={imgH} scale={scale} spacing={gridSpacing} />}
        </div>

        {/* RIGHT: Reconstruction */}
        <div className="flex-1 relative border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-900">
          <div className="absolute top-0 left-0 px-2 py-0.5 bg-teal-600/80 text-white text-[10px] font-medium rounded-br z-20">
            Rekonstruktion
          </div>

          {/* Rendered zones */}
          {grid.zones.map((zone) => (
            <ZoneRenderer key={zone.zone_index} zone={zone} scale={scale} fontSize={scaledFont} />
          ))}

          {/* Coordinate grid */}
          {showGrid && <CoordinateGrid imgW={imgW} imgH={imgH} scale={scale} spacing={gridSpacing} />}
        </div>
      </div>
    </div>
  )
}

// ---------------------------------------------------------------------------
// Coordinate grid overlay
// ---------------------------------------------------------------------------

function CoordinateGrid({ imgW, imgH, scale, spacing }: {
  imgW: number; imgH: number; scale: number; spacing: number
}) {
  const lines: JSX.Element[] = []

  // Vertical lines
  for (let x = 0; x <= imgW; x += spacing) {
    const px = x * scale
    lines.push(
      <div key={`v${x}`} className="absolute top-0 bottom-0 pointer-events-none" style={{ left: `${px}px`, width: '1px', background: 'rgba(0,150,255,0.2)' }}>
        <span className="absolute top-0 left-1 text-[8px] text-blue-400 font-mono">{x}</span>
      </div>
    )
  }

  // Horizontal lines
  for (let y = 0; y <= imgH; y += spacing) {
    const px = y * scale
    lines.push(
      <div key={`h${y}`} className="absolute left-0 right-0 pointer-events-none" style={{ top: `${px}px`, height: '1px', background: 'rgba(0,150,255,0.2)' }}>
        <span className="absolute left-1 top-0.5 text-[8px] text-blue-400 font-mono">{y}</span>
      </div>
    )
  }

  return <>{lines}</>
}

// ---------------------------------------------------------------------------
// Zone renderer (reconstruction side)
// ---------------------------------------------------------------------------

function ZoneRenderer({ zone, scale, fontSize }: {
  zone: GridZone; scale: number; fontSize: number
}) {
  const isBox = zone.zone_type === 'box'
  const boxColor = (zone as any).box_bg_hex || '#6b7280'

  if (!zone.cells || zone.cells.length === 0) return null

  const left = zone.bbox_px.x * scale
  const top = zone.bbox_px.y * scale
  const width = zone.bbox_px.w * scale
  const height = zone.bbox_px.h * scale

  const cellMap = new Map<string, GridEditorCell>()
  for (const cell of zone.cells) {
    cellMap.set(`${cell.row_index}_${cell.col_index}`, cell)
  }

  // Column widths scaled to zone
  const colWidths = zone.columns.map((col) => {
    const w = (col.x_max_px ?? 0) - (col.x_min_px ?? 0)
    return Math.max(5, w * scale)
  })
  const totalColW = colWidths.reduce((s, w) => s + w, 0)
  const colScale = totalColW > 0 ? width / totalColW : 1
  const scaledColWidths = colWidths.map((w) => w * colScale)

  const numCols = zone.columns.length

  return (
    <div
      className="absolute overflow-hidden"
      style={{
        left: `${left}px`,
        top: `${top}px`,
        width: `${width}px`,
        minHeight: `${height}px`,
        border: isBox ? `${Math.max(1.5, 2.5 * scale)}px solid ${boxColor}` : undefined,
        backgroundColor: isBox ? `${boxColor}08` : undefined,
        borderRadius: isBox ? `${Math.max(1, 3 * scale)}px` : undefined,
        fontSize: `${fontSize}px`,
        lineHeight: '1.25',
      }}
    >
      <div style={{ display: 'grid', gridTemplateColumns: scaledColWidths.map((w) => `${w.toFixed(1)}px`).join(' ') }}>
        {zone.rows.map((row) => {
          const isSpanning = zone.cells.some((c) => c.row_index === row.index && c.col_type === 'spanning_header')
          const measuredH = (row.y_max_px ?? 0) - (row.y_min_px ?? 0)
          const rowH = Math.max(fontSize * 1.3, measuredH * scale)

          return (
            <div key={row.index} style={{ display: 'contents' }}>
              {isSpanning ? (
                zone.cells
                  .filter((c) => c.row_index === row.index && c.col_type === 'spanning_header')
                  .sort((a, b) => a.col_index - b.col_index)
                  .map((cell) => {
                    const colspan = cell.colspan || numCols
                    const color = getCellColor(cell)
                    return (
                      <div
                        key={cell.cell_id}
                        className={`px-0.5 overflow-hidden ${row.is_header ? 'font-bold' : ''}`}
                        style={{
                          gridColumn: `${cell.col_index + 1} / ${cell.col_index + 1 + colspan}`,
                          minHeight: `${rowH}px`,
                          color: color || undefined,
                          whiteSpace: 'pre-wrap',
                        }}
                      >
                        {cell.text}
                      </div>
                    )
                  })
              ) : (
                zone.columns.map((col) => {
                  const cell = cellMap.get(`${row.index}_${col.index}`)
                  if (!cell) return <div key={col.index} style={{ minHeight: `${rowH}px` }} />
                  const color = getCellColor(cell)
                  const isBold = col.bold || cell.is_bold || row.is_header
                  const text = cell.text ?? ''

                  return (
                    <div
                      key={col.index}
                      className={`px-0.5 overflow-hidden ${isBold ? 'font-bold' : ''}`}
                      style={{
                        minHeight: `${rowH}px`,
                        color: color || undefined,
                        whiteSpace: text.includes('\n') ? 'pre-wrap' : 'nowrap',
                        textOverflow: text.includes('\n') ? undefined : 'ellipsis',
                      }}
                    >
                      {text}
                    </div>
                  )
                })
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}
