import React, { useRef, useState, useCallback } from 'react'
import { Play, Pause, Scissors, Trash2, Clock } from 'lucide-react'

interface Segmento {
  inicio: number
  fim: number
}

interface LiveCutterProps {
  file: File
  segmentos: Segmento[]
  onSegmentos: (segs: Segmento[]) => void
}

function fmtTime(s: number): string {
  const m = Math.floor(s / 60)
  const ss = (s % 60).toFixed(1).padStart(4, '0')
  return `${m}:${ss}`
}

export default function LiveCutter({ file, segmentos, onSegmentos }: LiveCutterProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [playing, setPlaying] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)
  const [marcadorInicio, setMarcadorInicio] = useState<number | null>(null)
  const videoUrl = URL.createObjectURL(file)

  const togglePlay = () => {
    const v = videoRef.current
    if (!v) return
    if (playing) v.pause()
    else v.play()
    setPlaying(!playing)
  }

  const handleTimeUpdate = () => {
    if (videoRef.current) setCurrentTime(videoRef.current.currentTime)
  }

  const handleLoadedMetadata = () => {
    if (videoRef.current) setDuration(videoRef.current.duration)
  }

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const t = parseFloat(e.target.value)
    if (videoRef.current) videoRef.current.currentTime = t
    setCurrentTime(t)
  }

  const marcarInicio = useCallback(() => {
    setMarcadorInicio(currentTime)
  }, [currentTime])

  const marcarFim = useCallback(() => {
    if (marcadorInicio === null) return
    const novo: Segmento = {
      inicio: marcadorInicio,
      fim: currentTime,
    }
    if (novo.fim <= novo.inicio) return
    onSegmentos([...segmentos, novo])
    setMarcadorInicio(null)
  }, [marcadorInicio, currentTime, segmentos, onSegmentos])

  const removerSegmento = (idx: number) => {
    onSegmentos(segmentos.filter((_, i) => i !== idx))
  }

  const duracaoTotal = segmentos.reduce((acc, s) => acc + (s.fim - s.inicio), 0)

  return (
    <div className="space-y-4">
      {/* Player */}
      <div className="bg-black rounded-xl overflow-hidden">
        <video
          ref={videoRef}
          src={videoUrl}
          className="w-full max-h-64 object-contain"
          onTimeUpdate={handleTimeUpdate}
          onLoadedMetadata={handleLoadedMetadata}
          onEnded={() => setPlaying(false)}
        />
      </div>

      {/* Controles */}
      <div className="space-y-2">
        {/* Timeline */}
        <div className="relative h-2">
          <input
            type="range"
            min={0}
            max={duration || 1}
            step={0.1}
            value={currentTime}
            onChange={handleSeek}
            className="w-full h-2 appearance-none bg-white/10 rounded-full cursor-pointer accent-indigo-500"
          />
          {/* Marcas dos segmentos */}
          {duration > 0 && segmentos.map((seg, i) => (
            <div
              key={i}
              className="absolute top-0 h-2 bg-indigo-500/40 rounded"
              style={{
                left: `${(seg.inicio / duration) * 100}%`,
                width: `${((seg.fim - seg.inicio) / duration) * 100}%`,
              }}
            />
          ))}
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={togglePlay}
            className="p-2 bg-indigo-600 hover:bg-indigo-500 rounded-lg transition-colors"
          >
            {playing ? <Pause size={16} /> : <Play size={16} />}
          </button>
          <span className="text-xs text-slate-400 font-mono tabular-nums">
            {fmtTime(currentTime)} / {fmtTime(duration)}
          </span>
        </div>
      </div>

      {/* Botoes de marcacao */}
      <div className="flex gap-2">
        <button
          onClick={marcarInicio}
          className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-medium transition-all border ${
            marcadorInicio !== null
              ? 'bg-amber-500/20 border-amber-500/40 text-amber-300'
              : 'bg-white/5 border-white/10 text-slate-300 hover:border-indigo-500/40'
          }`}
        >
          <Scissors size={14} />
          {marcadorInicio !== null ? `Inicio: ${fmtTime(marcadorInicio)}` : 'Marcar inicio'}
        </button>
        <button
          onClick={marcarFim}
          disabled={marcadorInicio === null}
          className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-medium transition-all border bg-white/5 border-white/10 text-slate-300 hover:border-emerald-500/40 disabled:opacity-40 disabled:cursor-not-allowed"
        >
          <Scissors size={14} />
          Marcar fim
        </button>
      </div>

      {/* Lista de segmentos */}
      {segmentos.length > 0 && (
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <p className="text-xs font-medium text-slate-400 uppercase tracking-wide">
              Segmentos selecionados
            </p>
            <span className="text-xs text-slate-500 flex items-center gap-1">
              <Clock size={11} />
              Total: {fmtTime(duracaoTotal)}
            </span>
          </div>
          {segmentos.map((seg, i) => (
            <div
              key={i}
              className="flex items-center justify-between bg-white/5 border border-white/10 rounded-lg px-3 py-2"
            >
              <span className="text-xs font-mono text-slate-300">
                #{i + 1} - {fmtTime(seg.inicio)} ate {fmtTime(seg.fim)}
              </span>
              <span className="text-xs text-slate-500 mr-3">
                {fmtTime(seg.fim - seg.inicio)}
              </span>
              <button
                onClick={() => removerSegmento(i)}
                className="text-slate-600 hover:text-red-400 transition-colors"
              >
                <Trash2 size={13} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
