import { useEffect, useRef, useState } from 'react'
import WaveSurfer from 'wavesurfer.js'
import { Play, Pause } from 'lucide-react'
import { mmss } from '@/lib/format'

interface Props {
  url: string
  dur: number
  /** called with current playback time (s) on every frame + on seek */
  onTime: (t: number) => void
}

/** A single take's transport: wavesurfer waveform, click-seek, Space=play/pause. */
export function WaveformPlayer({ url, dur, onTime }: Props) {
  const elRef = useRef<HTMLDivElement>(null)
  const wsRef = useRef<WaveSurfer | null>(null)
  const onTimeRef = useRef(onTime)
  onTimeRef.current = onTime

  const [playing, setPlaying] = useState(false)
  const [ready, setReady] = useState(false)
  const [t, setT] = useState(0)

  useEffect(() => {
    if (!elRef.current) return
    const ws = WaveSurfer.create({
      container: elRef.current,
      height: 76,
      waveColor: '#6a6a70', // ink-faint
      progressColor: '#e8e8ea', // ink
      cursorColor: '#d900ff', // brand magenta — the now
      cursorWidth: 2,
      barWidth: 2,
      barGap: 1,
      barRadius: 1,
      normalize: true,
      url,
    })
    wsRef.current = ws
    setReady(false)
    setPlaying(false)
    const emit = (time: number) => {
      setT(time)
      onTimeRef.current(time)
    }
    ws.on('ready', () => setReady(true))
    ws.on('timeupdate', emit)
    ws.on('interaction', () => emit(ws.getCurrentTime()))
    ws.on('play', () => setPlaying(true))
    ws.on('pause', () => setPlaying(false))
    ws.on('finish', () => setPlaying(false))
    return () => {
      ws.destroy()
    }
  }, [url])

  const toggle = () => wsRef.current?.playPause()

  return (
    <div
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.code === 'Space') {
          e.preventDefault()
          toggle()
        }
      }}
      className="group rounded-md outline-none focus-visible:ring-2 focus-visible:ring-magenta/60"
    >
      <div className="flex items-center gap-3">
        <button
          onClick={toggle}
          disabled={!ready}
          aria-label={playing ? 'Pause' : 'Play'}
          className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md
                     bg-ink text-surface transition-opacity hover:opacity-90
                     disabled:opacity-30"
        >
          {playing ? <Pause size={18} fill="currentColor" /> : <Play size={18} fill="currentColor" />}
        </button>
        <div ref={elRef} className="min-w-0 flex-1" />
      </div>
      <div className="mt-1 flex justify-between font-mono text-xs text-ink-muted tnum">
        <span>{ready ? mmss(t) : 'loading…'}</span>
        <span>{mmss(dur)}</span>
      </div>
    </div>
  )
}
