'use client'

import { useEffect, useRef, useState } from 'react'
import type { StructureBox, StructureGraphic } from '@/app/(admin)/ai/ocr-kombi/types'
import type { WordPosition } from './usePixelWordPositions'
import type { EditableCell, PageRegion, RowItem, PageZone } from './StepReconstructionTypes'
import { adjustCellForBoxZones } from './StepReconstructionTypes'
import { StructureLayer } from './StructureLayer'

interface ReconstructionOverlayProps {
  cells: EditableCell[]
  dewarpedUrl: string
  imageNaturalSize: { w: number; h: number } | null
  parentColumns: PageRegion[]
  parentRows: RowItem[]
  parentZones: PageZone[]
  structureBoxes: StructureBox[]
  structureGraphics: StructureGraphic[]
  showStructure: boolean
  fontScale: number
  globalBold: boolean
  boxZonesPct: { topPct: number; bottomPct: number }[]
  cellWordPositions: Map<string, WordPosition[]>
  onTextChange: (cellId: string, newText: string) => void
  onKeyDown: (e: React.KeyboardEvent, cellId: string) => void
  onResetCell: (cellId: string) => void
  onImageNaturalSize: (size: { w: number; h: number }) => void
  getDisplayText: (cell: EditableCell) => string
  isEdited: (cell: EditableCell) => boolean
}

export function ReconstructionOverlay({
  cells,
  dewarpedUrl,
  imageNaturalSize,
  parentColumns,
  parentRows,
  parentZones,
  structureBoxes,
  structureGraphics,
  showStructure,
  fontScale,
  globalBold,
  boxZonesPct,
  cellWordPositions,
  onTextChange,
  onKeyDown,
  onResetCell,
  onImageNaturalSize,
  getDisplayText,
  isEdited,
}: ReconstructionOverlayProps) {
  const reconRef = useRef<HTMLDivElement>(null)
  const [reconWidth, setReconWidth] = useState(0)

  // Track reconstruction container width for font size calculation
  useEffect(() => {
    const el = reconRef.current
    if (!el) return
    const obs = new ResizeObserver(entries => {
      for (const entry of entries) setReconWidth(entry.contentRect.width)
    })
    obs.observe(el)
    return () => obs.disconnect()
  }, [])

  const imgW = imageNaturalSize?.w || 1
  const imgH = imageNaturalSize?.h || 1
  const aspect = imgH / imgW
  const containerH = reconWidth * aspect

  return (
    <div className="grid grid-cols-2 gap-4">
      {/* Left: Original image */}
      <div>
        <div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
          Originalbild
        </div>
        <div className="border rounded-lg overflow-hidden dark:border-gray-700 bg-gray-50 dark:bg-gray-900 sticky top-4">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={dewarpedUrl}
            alt="Original"
            className="w-full h-auto"
            onLoad={(e) => {
              const img = e.target as HTMLImageElement
              onImageNaturalSize({ w: img.naturalWidth, h: img.naturalHeight })
            }}
          />
        </div>
      </div>

      {/* Right: Reconstructed table overlay */}
      <div>
        <div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
          Rekonstruktion ({cells.length} Zellen)
        </div>
        <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white">
          <div
            ref={reconRef}
            className="relative"
            style={{ aspectRatio: `${imgW} / ${imgH}` }}
          >
            {/* Column lines */}
            {parentColumns
              .filter(c => !['header', 'footer'].includes(c.type))
              .map((col, i) => (
                <div
                  key={`col-${i}`}
                  className="absolute top-0 bottom-0 border-l border-gray-300/50"
                  style={{ left: `${(col.x / imgW) * 100}%` }}
                />
              ))}

            {/* Row lines */}
            {parentRows.map((row, i) => (
              <div
                key={`row-${i}`}
                className="absolute left-0 right-0 border-t border-gray-300/50"
                style={{ top: `${(row.y / imgH) * 100}%` }}
              />
            ))}

            {/* Box zone highlight */}
            {parentZones
              .filter(z => z.zone_type === 'box' && z.box)
              .map((z, i) => {
                const box = z.box!
                return (
                  <div
                    key={`box-${i}`}
                    className="absolute border-2 border-blue-400/30 bg-blue-50/10 pointer-events-none"
                    style={{
                      left: `${(box.x / imgW) * 100}%`,
                      top: `${(box.y / imgH) * 100}%`,
                      width: `${(box.width / imgW) * 100}%`,
                      height: `${(box.height / imgH) * 100}%`,
                    }}
                  />
                )
              })}

            {/* Structure elements (boxes, graphics) */}
            <StructureLayer
              boxes={structureBoxes}
              graphics={structureGraphics}
              imgW={imgW}
              imgH={imgH}
              show={showStructure}
            />

            {/* Pixel-positioned words / editable inputs */}
            {cells.map((cell) => renderOverlayCell(
              cell,
              getDisplayText(cell),
              isEdited(cell),
              cellWordPositions.get(cell.cellId),
              adjustCellForBoxZones(cell.bboxPct, cell.cellId, boxZonesPct),
              containerH,
              fontScale,
              globalBold,
              onTextChange,
              onKeyDown,
              onResetCell,
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}

// --- Cell rendering for overlay mode ---

function renderOverlayCell(
  cell: EditableCell,
  displayText: string,
  edited: boolean,
  wordPos: WordPosition[] | undefined,
  adjBbox: { x: number; y: number; w: number; h: number },
  containerH: number,
  fontScale: number,
  globalBold: boolean,
  onTextChange: (cellId: string, text: string) => void,
  onKeyDown: (e: React.KeyboardEvent, cellId: string) => void,
  onResetCell: (cellId: string) => void,
): React.ReactNode {
  const cellHeightPx = containerH * (adjBbox.h / 100)

  // Pixel-analysed: render word-groups at detected positions as inputs
  if (wordPos && wordPos.length > 0) {
    return wordPos.map((wp, i) => {
      const autoFontPx = cellHeightPx * wp.fontRatio * fontScale
      const fs = Math.max(6, autoFontPx)

      // For multi-group cells, render as span (read-only positioned)
      if (wordPos.length > 1) {
        return (
          <span
            key={`${cell.cellId}_wp_${i}`}
            className="absolute leading-none pointer-events-none select-none"
            style={{
              left: `${wp.xPct}%`,
              top: `${adjBbox.y}%`,
              width: `${wp.wPct}%`,
              height: `${adjBbox.h}%`,
              fontSize: `${fs}px`,
              fontWeight: globalBold ? 'bold' : (cell.colType === 'column_en' ? 'bold' : 'normal'),
              fontFamily: "'Liberation Sans', Arial, sans-serif",
              display: 'flex',
              alignItems: 'center',
              whiteSpace: 'nowrap',
              overflow: 'visible',
              color: '#1a1a1a',
            }}
          >
            {wp.text}
          </span>
        )
      }

      // Single group: render as editable input at pixel position
      return (
        <div key={`${cell.cellId}_wp_${i}`} className="absolute group" style={{
          left: `${wp.xPct}%`,
          top: `${adjBbox.y}%`,
          width: `${wp.wPct}%`,
          height: `${adjBbox.h}%`,
        }}>
          <input
            id={`cell-${cell.cellId}`}
            type="text"
            value={displayText}
            onChange={(e) => onTextChange(cell.cellId, e.target.value)}
            onKeyDown={(e) => onKeyDown(e, cell.cellId)}
            className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
              edited ? 'bg-green-50/30' : ''
            }`}
            style={{
              fontSize: `${fs}px`,
              fontWeight: globalBold ? 'bold' : (cell.colType === 'column_en' ? 'bold' : 'normal'),
              fontFamily: "'Liberation Sans', Arial, sans-serif",
              lineHeight: '1',
              color: '#1a1a1a',
            }}
            title={`${cell.cellId} (${cell.colType})`}
          />
          {edited && (
            <button
              onClick={() => onResetCell(cell.cellId)}
              className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
              title="Zuruecksetzen"
            >
              &times;
            </button>
          )}
        </div>
      )
    })
  }

  // Fallback: no pixel data — single input at cell bbox
  if (!cell.text) return null

  const fontSize = Math.max(6, cellHeightPx * fontScale)
  return (
    <div key={cell.cellId} className="absolute group" style={{
      left: `${adjBbox.x}%`,
      top: `${adjBbox.y}%`,
      width: `${adjBbox.w}%`,
      height: `${adjBbox.h}%`,
    }}>
      <input
        id={`cell-${cell.cellId}`}
        type="text"
        value={displayText}
        onChange={(e) => onTextChange(cell.cellId, e.target.value)}
        onKeyDown={(e) => onKeyDown(e, cell.cellId)}
        className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
          edited ? 'bg-green-50/30' : ''
        }`}
        style={{
          fontSize: `${fontSize}px`,
          fontWeight: globalBold ? 'bold' : 'normal',
          fontFamily: "'Liberation Sans', Arial, sans-serif",
          lineHeight: '1',
          color: '#1a1a1a',
        }}
        title={`${cell.cellId} (${cell.colType})`}
      />
      {edited && (
        <button
          onClick={() => onResetCell(cell.cellId)}
          className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
          title="Zuruecksetzen"
        >
          &times;
        </button>
      )}
    </div>
  )
}
