'use client'

import type { GridCell, ImageRegionWithState } from './ground-truth-types'

interface ReconstructionPanelProps {
  cells: GridCell[]
  aspect: number
  zoom: number
  reconWidth: number
  imageRegions: ImageRegionWithState[]
  drawingRegion: boolean
  dragStart: { x: number; y: number } | null
  dragEnd: { x: number; y: number } | null
  panelRef: React.RefObject<HTMLDivElement | null>
  reconRef: React.RefObject<HTMLDivElement | null>
  onScroll: () => void
  onToggleDrawing: () => void
  onMouseDown: (e: React.MouseEvent<HTMLDivElement>) => void
  onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void
  onMouseUp: () => void
}

export function ReconstructionPanel({
  cells, aspect, zoom, reconWidth, imageRegions, drawingRegion,
  dragStart, dragEnd, panelRef, reconRef,
  onScroll, onToggleDrawing, onMouseDown, onMouseMove, onMouseUp,
}: ReconstructionPanelProps) {
  return (
    <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 flex items-center justify-between">
        <span>Rekonstruktion</span>
        <button
          onClick={onToggleDrawing}
          className={`text-xs px-2 py-0.5 rounded ${drawingRegion ? 'bg-indigo-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'}`}
        >
          {drawingRegion ? 'Region zeichnen...' : '+ Region'}
        </button>
      </div>
      <div
        ref={panelRef}
        className="flex-1 overflow-auto"
        onScroll={onScroll}
      >
        <div style={{ width: `${zoom}%`, minWidth: '100%' }}>
        {/* Reconstruction container */}
        <div
          ref={reconRef}
          className="relative bg-white"
          style={{
            paddingBottom: `${aspect * 100}%`,
            cursor: drawingRegion ? 'crosshair' : 'default',
          }}
          onMouseDown={onMouseDown}
          onMouseMove={onMouseMove}
          onMouseUp={onMouseUp}
        >
          {/* Row separator lines -- derive from cells */}
          <RowSeparators cells={cells} />

          {/* Cell texts -- black on white, font size derived from cell height */}
          {cells.map(cell => {
            if (!cell.bbox_pct || !cell.text) return null
            const containerH = reconWidth * aspect
            const cellHeightPx = containerH * (cell.bbox_pct.h / 100)
            const fontSize = Math.max(6, cellHeightPx * 0.7)
            return (
              <span
                key={cell.cell_id}
                className="absolute leading-none overflow-hidden whitespace-nowrap"
                style={{
                  left: `${cell.bbox_pct.x}%`,
                  top: `${cell.bbox_pct.y}%`,
                  width: `${cell.bbox_pct.w}%`,
                  height: `${cell.bbox_pct.h}%`,
                  color: '#1a1a1a',
                  fontSize: `${fontSize}px`,
                  fontWeight: cell.is_bold ? 'bold' : 'normal',
                  fontFamily: "'Liberation Sans', 'DejaVu Sans', Arial, sans-serif",
                  display: 'flex',
                  alignItems: 'center',
                  padding: '0 1px',
                }}
                title={`${cell.cell_id}: ${cell.text}`}
              >
                {cell.text}
              </span>
            )
          })}

          {/* Generated images at region positions */}
          {imageRegions.map((region, i) => (
            <div
              key={`region-${i}`}
              className="absolute border-2 border-dashed border-indigo-400"
              style={{
                left: `${region.bbox_pct.x}%`,
                top: `${region.bbox_pct.y}%`,
                width: `${region.bbox_pct.w}%`,
                height: `${region.bbox_pct.h}%`,
              }}
            >
              {region.image_b64 ? (
                <img src={region.image_b64} alt={region.description} className="w-full h-full object-cover" />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-indigo-50/50 text-indigo-400 text-[0.5em]">
                  {region.generating ? '...' : `Bild ${i + 1}`}
                </div>
              )}
            </div>
          ))}

          {/* Drawing rectangle */}
          {dragStart && dragEnd && (
            <div
              className="absolute border-2 border-dashed border-red-500 bg-red-100/20 pointer-events-none"
              style={{
                left: `${Math.min(dragStart.x, dragEnd.x)}%`,
                top: `${Math.min(dragStart.y, dragEnd.y)}%`,
                width: `${Math.abs(dragEnd.x - dragStart.x)}%`,
                height: `${Math.abs(dragEnd.y - dragStart.y)}%`,
              }}
            />
          )}
        </div>
        </div>
      </div>
    </div>
  )
}

/** Row separator lines derived from first-column cells */
function RowSeparators({ cells }: { cells: GridCell[] }) {
  const rowYs = new Set<number>()
  for (const cell of cells) {
    if (cell.col_index === 0 && cell.bbox_pct) {
      rowYs.add(cell.bbox_pct.y)
    }
  }
  return (
    <>
      {Array.from(rowYs).map((y, i) => (
        <div
          key={`row-${i}`}
          className="absolute left-0 right-0"
          style={{
            top: `${y}%`,
            height: '1px',
            backgroundColor: 'rgba(0,0,0,0.06)',
          }}
        />
      ))}
    </>
  )
}
