import { useEffect, useRef } from 'react'
import type { StepGraphSample } from './gesture/types'

interface Props {
  samples: StepGraphSample[]
  thresholdX: number
  thresholdZ: number
  reset: number
  width?: number
  height?: number
}

function drawGraph(
  ctx: CanvasRenderingContext2D,
  samples: StepGraphSample[],
  w: number,
  h: number,
  title: string,
  getLeft: (s: StepGraphSample) => number,
  getRight: (s: StepGraphSample) => number,
  threshold: number,
  reset: number,
  activeSignals: string[], // which step signals to highlight for this graph
) {
  // Background
  ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
  ctx.fillRect(0, 0, w, h)

  if (samples.length < 2) {
    ctx.fillStyle = '#888'
    ctx.font = '12px monospace'
    ctx.fillText(title + ' (waiting...)', 4, 14)
    return
  }

  // Y range: symmetric around 0, at least ±threshold
  const allVals = samples.flatMap((s) => [getLeft(s), getRight(s)])
  const maxAbs = Math.max(threshold * 1.5, ...allVals.map(Math.abs))

  const toY = (v: number) => h / 2 + (v / maxAbs) * (h / 2 - 4)
  const toX = (i: number) => (i / (samples.length - 1)) * w

  // Highlight active step segments
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]
    if (s.activeStep && activeSignals.includes(s.activeStep)) {
      const x0 = toX(i)
      const x1 = i < samples.length - 1 ? toX(i + 1) : x0 + 2
      ctx.fillStyle = 'rgba(255, 255, 0, 0.15)'
      ctx.fillRect(x0, 0, x1 - x0, h)
    }
  }

  // Zero line
  ctx.strokeStyle = '#555'
  ctx.lineWidth = 1
  ctx.setLineDash([2, 2])
  ctx.beginPath()
  ctx.moveTo(0, h / 2)
  ctx.lineTo(w, h / 2)
  ctx.stroke()
  ctx.setLineDash([])

  // Threshold lines (positive and negative)
  ctx.strokeStyle = '#ff4444'
  ctx.lineWidth = 1
  ctx.setLineDash([4, 4])
  for (const sign of [1, -1]) {
    ctx.beginPath()
    ctx.moveTo(0, toY(threshold * sign))
    ctx.lineTo(w, toY(threshold * sign))
    ctx.stroke()
  }
  ctx.setLineDash([])

  // Reset lines (positive and negative)
  ctx.strokeStyle = '#ffaa00'
  ctx.lineWidth = 1
  ctx.setLineDash([2, 4])
  for (const sign of [1, -1]) {
    ctx.beginPath()
    ctx.moveTo(0, toY(reset * sign))
    ctx.lineTo(w, toY(reset * sign))
    ctx.stroke()
  }
  ctx.setLineDash([])

  // Left heel line (cyan)
  ctx.strokeStyle = '#00ffcc'
  ctx.lineWidth = 2
  ctx.beginPath()
  for (let i = 0; i < samples.length; i++) {
    const x = toX(i), y = toY(getLeft(samples[i]))
    if (i === 0) ctx.moveTo(x, y)
    else ctx.lineTo(x, y)
  }
  ctx.stroke()

  // Right heel line (magenta)
  ctx.strokeStyle = '#ff44ff'
  ctx.lineWidth = 2
  ctx.beginPath()
  for (let i = 0; i < samples.length; i++) {
    const x = toX(i), y = toY(getRight(samples[i]))
    if (i === 0) ctx.moveTo(x, y)
    else ctx.lineTo(x, y)
  }
  ctx.stroke()

  // Labels
  ctx.font = 'bold 16px monospace'
  ctx.fillStyle = '#fff'
  ctx.fillText(title, 6, 20)
  ctx.fillStyle = '#00ffcc'
  ctx.fillText('L', w - 40, 20)
  ctx.fillStyle = '#ff44ff'
  ctx.fillText('R', w - 20, 20)
  // Threshold/reset labels
  ctx.font = '14px monospace'
  ctx.fillStyle = '#ff4444'
  ctx.fillText(`thr ${threshold.toFixed(2)}`, 6, h - 22)
  ctx.fillStyle = '#ffaa00'
  ctx.fillText(`rst ${reset.toFixed(2)}`, 6, h - 6)
}

export function StepGraphs({ samples, thresholdX, thresholdZ, reset, width = 500, height = 220 }: Props) {
  const lrRef = useRef<HTMLCanvasElement>(null)
  const fbRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    const lrCanvas = lrRef.current
    const fbCanvas = fbRef.current
    if (!lrCanvas || !fbCanvas) return

    const lrCtx = lrCanvas.getContext('2d')!
    const fbCtx = fbCanvas.getContext('2d')!

    drawGraph(lrCtx, samples, width, height, 'LEFT / RIGHT (X)',
      (s) => s.leftX, (s) => s.rightX, thresholdX, reset,
      ['step-left', 'step-right'])

    drawGraph(fbCtx, samples, width, height, 'FORWARD / BACK (Z)',
      (s) => s.leftZ, (s) => s.rightZ, thresholdZ, reset,
      ['step-forward', 'step-back'])
  }, [samples, thresholdX, thresholdZ, reset, width, height])

  return (
    <div style={{ position: 'fixed', left: 10, top: 80, zIndex: 100, display: 'flex', flexDirection: 'column', gap: 4 }}>
      <canvas ref={lrRef} width={width} height={height} />
      <canvas ref={fbRef} width={width} height={height} />
    </div>
  )
}
