'use client'

import { useRef, useState } from 'react'
import { Play, Pause, Mic } from 'lucide-react'

export function VoiceNotePlayer({ path, mime }: { path: string; mime: string | null }) {
  const ref = useRef<HTMLAudioElement>(null)
  const [playing, setPlaying] = useState(false)
  const [duration, setDuration] = useState<number | null>(null)
  const [current, setCurrent] = useState(0)

  const toggle = () => {
    const el = ref.current
    if (!el) return
    if (el.paused) {
      el.play()
      setPlaying(true)
    } else {
      el.pause()
      setPlaying(false)
    }
  }

  return (
    <div className="flex items-center gap-3 p-3 rounded-xl border bg-card">
      <button
        type="button"
        onClick={toggle}
        className="size-10 rounded-full bg-primary text-primary-foreground flex items-center justify-center shrink-0"
        aria-label={playing ? 'Pause' : 'Play'}
      >
        {playing ? <Pause className="size-4" /> : <Play className="size-4 translate-x-[1px]" />}
      </button>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1.5 text-sm font-medium">
          <Mic className="size-3.5 text-muted-foreground" />
          Voice note
        </div>
        <div className="text-xs text-muted-foreground tabular-nums">
          {formatSeconds(current)}
          {duration != null && ` / ${formatSeconds(duration)}`}
        </div>
      </div>
      <audio
        ref={ref}
        src={`/api/uploads/${path}`}
        preload="metadata"
        onLoadedMetadata={e => {
          const d = (e.target as HTMLAudioElement).duration
          if (Number.isFinite(d)) setDuration(d)
        }}
        onTimeUpdate={e => setCurrent((e.target as HTMLAudioElement).currentTime)}
        onEnded={() => setPlaying(false)}
        onPause={() => setPlaying(false)}
        className="hidden"
      >
        {mime && <source src={`/api/uploads/${path}`} type={mime} />}
      </audio>
    </div>
  )
}

function formatSeconds(s: number) {
  const m = Math.floor(s / 60)
  const r = Math.floor(s % 60)
  return `${m}:${String(r).padStart(2, '0')}`
}
