import { useEffect, useMemo, useRef, useState } from 'react'
import type { RawSignal } from '../sim/simulate.ts'
import { KSPACE_MODES, renderKspace } from './kspace.ts'
import type { KspaceMode } from './kspace.ts'

export function KspaceView({ signal, elapsedMs }: { signal: RawSignal; elapsedMs: number }) {
  const [mode, setMode] = useState<KspaceMode>('log-magnitude')
  const canvasRef = useRef<HTMLCanvasElement>(null)

  const image = useMemo(() => renderKspace(signal, mode), [signal, mode])

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    canvas.width = image.width
    canvas.height = image.height
    const ctx = canvas.getContext('2d')
    if (!ctx) return
    const imageData = ctx.createImageData(image.width, image.height)
    imageData.data.set(image.rgba)
    ctx.putImageData(imageData, 0, 0)
  }, [image])

  const totalSamples = signal.re.length

  return (
    <div className="kspace">
      <div className="kspace-toolbar">
        <div className="segmented">
          {KSPACE_MODES.map((m) => (
            <button
              key={m.id}
              className={m.id === mode ? 'active' : ''}
              onClick={() => setMode(m.id)}
              type="button"
            >
              {m.label}
            </button>
          ))}
        </div>
      </div>
      <div className="kspace-canvas-wrap">
        <canvas ref={canvasRef} className="kspace-canvas" />
      </div>
      <div className="kspace-info">
        <span>
          {signal.numReadouts} readouts × {signal.maxSamplesPerReadout} samples
        </span>
        <span>{totalSamples.toLocaleString()} complex points</span>
        <span>
          {image.scale.label
            ? `${image.scale.label}: ${image.scale.min.toFixed(0)} … ${image.scale.max.toFixed(0)}`
            : `scale: 0 … ${image.scale.max.toPrecision(3)}`}
        </span>
        <span>simulated in {(elapsedMs / 1000).toFixed(1)} s</span>
      </div>
    </div>
  )
}
