import { useState, useCallback, useEffect, useRef } from 'react'
import { Film, Scissors, Music, Type, LogOut, Wand2, Ban, ImagePlus } from 'lucide-react'
import { supabase } from '../lib/supabase'
import UploadZone from '../components/UploadZone'
import LiveCutter from '../components/LiveCutter'
import JobStatus from '../components/JobStatus'
import ResultCard from '../components/ResultCard'
import MusicDrawer, { Track } from '../components/MusicDrawer'

const API_URL = import.meta.env.VITE_API_URL || 'https://video.agenciaclimb.com.br'

interface Segmento {
  inicio: number
  fim: number
}

interface JobState {
  id: string
  status: string
  progresso: number
  mensagem: string
  video_url?: string
}

const ESTILOS_LEGENDA = [
  { value: 'karaoke_ig', label: 'Karaokê IG', desc: 'Pill laranja word-level' },
  { value: 'branca', label: 'Branca', desc: 'Texto branco com contorno' },
  { value: 'amarela', label: 'Amarela', desc: 'Texto amarelo estilo viral' },
  { value: 'karaoke', label: 'Karaokê clássico', desc: 'Cor amarela na palavra' },
]

const TAMANHOS_LEGENDA = [
  { value: 'pequeno', label: 'Pequeno' },
  { value: 'medio', label: 'Médio' },
  { value: 'grande', label: 'Grande' },
]

const MOOD_LABELS_PT: Record<string, string> = {
  upbeat: 'Energético',
  corporate: 'Profissional',
  inspiring: 'Inspirador',
  calm: 'Calmo',
  cinematic: 'Cinematográfico',
}

export default function Editor() {
  const [aba, setAba] = useState<'clip' | 'live'>('clip')
  const [arquivo, setArquivo] = useState<File | null>(null)
  const [segmentos, setSegmentos] = useState<Segmento[]>([])
  const [estilo, setEstilo] = useState('karaoke_ig')
  const [tamanhoLegenda, setTamanhoLegenda] = useState('medio')
  const [usarLegenda, setUsarLegenda] = useState(true)
  const [usarBroll, setUsarBroll] = useState(true)
  // Trilha sonora: null = "sem música"; track = trilha selecionada
  const [trilha, setTrilha] = useState<Track | null>(null)
  const [volumeMusica, setVolumeMusica] = useState(12) // 0..50
  const [drawerAberto, setDrawerAberto] = useState(false)
  const [enviando, setEnviando] = useState(false)
  const [erro, setErro] = useState('')
  const [job, setJob] = useState<JobState | null>(null)
  const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const clearArquivo = useCallback(() => {
    setArquivo(null)
    setSegmentos([])
  }, [])

  // Polling do job
  useEffect(() => {
    if (!job || job.status === 'concluido' || job.status === 'erro') {
      if (pollingRef.current) clearInterval(pollingRef.current)
      return
    }

    pollingRef.current = setInterval(async () => {
      try {
        const r = await fetch(`${API_URL}/api/job/${job.id}`)
        if (!r.ok) return
        const data = await r.json()
        setJob(prev => prev ? { ...prev, ...data } : null)
      } catch {
        // ignora erros de rede temporários
      }
    }, 3000)

    return () => {
      if (pollingRef.current) clearInterval(pollingRef.current)
    }
  }, [job?.id, job?.status])

  const enviar = async () => {
    if (!arquivo) return
    if (aba === 'live' && segmentos.length === 0) {
      setErro('Selecione ao menos um segmento antes de gerar.')
      return
    }

    setEnviando(true)
    setErro('')
    setJob(null)

    const form = new FormData()
    form.append('video', arquivo)
    form.append('modo', aba)

    // 3 toggles independentes
    form.append('usar_legenda', usarLegenda ? 'true' : 'false')
    form.append('usar_broll', usarBroll ? 'true' : 'false')

    // Música: se há trilha selecionada, manda usar_musica=true + musica_id
    // Se null (sem música), usar_musica=false
    if (trilha) {
      form.append('usar_musica', 'true')
      form.append('musica_id', trilha.id)
      form.append('volume_musica', String(volumeMusica))
    } else {
      form.append('usar_musica', 'false')
    }

    form.append('estilo_legenda', estilo)
    form.append('tamanho_legenda', tamanhoLegenda)
    if (aba === 'live') {
      form.append('segmentos', JSON.stringify(segmentos))
    }

    try {
      const r = await fetch(`${API_URL}/api/processar`, {
        method: 'POST',
        body: form,
      })
      const data = await r.json()
      if (!r.ok) throw new Error(data.erro || 'Erro ao iniciar processamento.')
      setJob({
        id: data.job_id,
        status: 'fila',
        progresso: 0,
        mensagem: 'Na fila...',
      })
    } catch (e: unknown) {
      setErro(e instanceof Error ? e.message : 'Erro ao conectar com o servidor.')
    } finally {
      setEnviando(false)
    }
  }

  const resetar = () => {
    setJob(null)
    setArquivo(null)
    setSegmentos([])
    setErro('')
  }

  const handleLogout = async () => {
    await supabase.auth.signOut()
  }

  const processando = job && job.status !== 'concluido' && job.status !== 'erro'
  const concluido = job?.status === 'concluido'
  const jobErro = job?.status === 'erro'

  return (
    <div className="min-h-screen">
      {/* Header */}
      <header className="border-b border-white/8 px-4 py-4 flex items-center justify-between max-w-2xl mx-auto">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-indigo-600/20 border border-indigo-500/30 flex items-center justify-center">
            <Film size={16} className="text-indigo-400" />
          </div>
          <div>
            <h1 className="text-sm font-bold text-white leading-none">Reel Editor</h1>
            <p className="text-[10px] text-slate-600 mt-0.5">Climb Digital</p>
          </div>
        </div>
        <button
          onClick={handleLogout}
          className="text-slate-500 hover:text-slate-300 transition-colors p-2"
          title="Sair"
        >
          <LogOut size={16} />
        </button>
      </header>

      {/* Content */}
      <main className="max-w-2xl mx-auto px-4 py-6 space-y-6">

        {/* Resultado - aparece quando concluido */}
        {concluido && job && (
          <ResultCard
            jobId={job.id}
            apiUrl={API_URL}
            onReset={resetar}
          />
        )}

        {/* Status do job em andamento */}
        {(processando || jobErro) && job && (
          <JobStatus
            status={job.status}
            progresso={job.progresso}
            mensagem={job.mensagem}
          />
        )}

        {/* Formulario - esconde durante processamento */}
        {!processando && !concluido && (
          <>
            {/* Abas */}
            <div className="flex bg-white/5 border border-white/10 rounded-xl p-1 gap-1">
              <button
                onClick={() => { setAba('clip'); clearArquivo() }}
                className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-all ${
                  aba === 'clip'
                    ? 'bg-indigo-600 text-white shadow-lg'
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                <Film size={15} />
                Clip Gravado
              </button>
              <button
                onClick={() => { setAba('live'); clearArquivo() }}
                className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm font-medium transition-all ${
                  aba === 'live'
                    ? 'bg-indigo-600 text-white shadow-lg'
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                <Scissors size={15} />
                Cortar Live
              </button>
            </div>

            {/* Conteudo da aba */}
            <div className="bg-white/3 border border-white/8 rounded-xl p-5 space-y-5">
              {aba === 'clip' ? (
                <>
                  <div>
                    <h2 className="text-sm font-semibold text-slate-200 mb-3">
                      Envie seu clip
                    </h2>
                    <UploadZone
                      file={arquivo}
                      onFile={setArquivo}
                      onClear={clearArquivo}
                      label="Arraste o vídeo (talking head, shorts, etc.)"
                    />
                  </div>
                </>
              ) : (
                <>
                  <div>
                    <h2 className="text-sm font-semibold text-slate-200 mb-1">
                      Envie sua live gravada
                    </h2>
                    <p className="text-xs text-slate-500 mb-3">
                      Depois do upload, marque os trechos que quer usar no Reel.
                    </p>
                    {!arquivo ? (
                      <UploadZone
                        file={arquivo}
                        onFile={setArquivo}
                        onClear={clearArquivo}
                        label="Arraste a live ou gravação longa"
                      />
                    ) : (
                      <LiveCutter
                        file={arquivo}
                        segmentos={segmentos}
                        onSegmentos={setSegmentos}
                      />
                    )}
                  </div>
                  {arquivo && (
                    <button
                      onClick={clearArquivo}
                      className="text-xs text-slate-500 hover:text-slate-300 transition-colors"
                    >
                      Trocar vídeo
                    </button>
                  )}
                </>
              )}

              {/* Opcoes */}
              <div className="space-y-4 pt-2 border-t border-white/8">
                {/* === LEGENDA === */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="flex items-center gap-1.5 text-xs font-medium text-slate-400 uppercase tracking-wide">
                      <Type size={12} />
                      Legenda automática
                    </label>
                    <button
                      onClick={() => setUsarLegenda(v => !v)}
                      className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium border transition-all ${
                        usarLegenda
                          ? 'border-indigo-500/60 bg-indigo-600/20 text-indigo-300'
                          : 'border-white/10 bg-white/5 text-slate-500'
                      }`}
                    >
                      <span className={`w-1.5 h-1.5 rounded-full ${usarLegenda ? 'bg-indigo-400' : 'bg-slate-500'}`} />
                      {usarLegenda ? 'Ativado' : 'Desligado'}
                    </button>
                  </div>

                  {usarLegenda && (
                    <div className="space-y-3">
                      <div className="grid grid-cols-2 gap-2">
                        {ESTILOS_LEGENDA.map(e => (
                          <button
                            key={e.value}
                            onClick={() => setEstilo(e.value)}
                            className={`py-2 px-3 rounded-lg border text-xs text-center transition-all ${
                              estilo === e.value
                                ? 'border-indigo-500/60 bg-indigo-600/20 text-indigo-300'
                                : 'border-white/10 text-slate-500 hover:border-white/20 hover:text-slate-300'
                            }`}
                          >
                            <span className="font-medium block">{e.label}</span>
                            <span className="text-[10px] opacity-70">{e.desc}</span>
                          </button>
                        ))}
                      </div>

                      <div>
                        <p className="text-[10px] uppercase tracking-wide text-slate-500 mb-1.5">Tamanho</p>
                        <div className="grid grid-cols-3 gap-2">
                          {TAMANHOS_LEGENDA.map(t => (
                            <button
                              key={t.value}
                              onClick={() => setTamanhoLegenda(t.value)}
                              className={`py-1.5 px-3 rounded-lg border text-xs text-center transition-all ${
                                tamanhoLegenda === t.value
                                  ? 'border-indigo-500/60 bg-indigo-600/20 text-indigo-300'
                                  : 'border-white/10 text-slate-500 hover:border-white/20 hover:text-slate-300'
                              }`}
                            >
                              {t.label}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* === B-ROLL === */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="flex items-center gap-1.5 text-xs font-medium text-slate-400 uppercase tracking-wide">
                      <ImagePlus size={12} />
                      B-roll automático
                    </label>
                    <button
                      onClick={() => setUsarBroll(v => !v)}
                      className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium border transition-all ${
                        usarBroll
                          ? 'border-indigo-500/60 bg-indigo-600/20 text-indigo-300'
                          : 'border-white/10 bg-white/5 text-slate-500'
                      }`}
                    >
                      <span className={`w-1.5 h-1.5 rounded-full ${usarBroll ? 'bg-indigo-400' : 'bg-slate-500'}`} />
                      {usarBroll ? 'Ativado' : 'Desligado'}
                    </button>
                  </div>
                  <p className="text-[11px] text-slate-500">
                    {usarBroll
                      ? 'A IA escolhe vídeos do Pexels alinhados à fala.'
                      : 'Só o vídeo principal, sem cortes de apoio.'}
                  </p>
                </div>

                {/* === MÚSICA === */}
                <div>
                  <label className="flex items-center gap-1.5 text-xs font-medium text-slate-400 uppercase tracking-wide mb-2">
                    <Music size={12} />
                    Trilha sonora
                  </label>
                  <button
                    onClick={() => setDrawerAberto(true)}
                    className={`w-full flex items-center gap-3 p-3 rounded-lg border transition-all text-left ${
                      trilha
                        ? 'border-indigo-500/60 bg-indigo-600/10 hover:bg-indigo-600/15'
                        : 'border-white/10 bg-white/3 hover:bg-white/5'
                    }`}
                  >
                    <div className={`w-9 h-9 rounded-lg flex items-center justify-center ${
                      trilha ? 'bg-indigo-600/30' : 'bg-white/5'
                    }`}>
                      {trilha
                        ? <Music size={15} className="text-indigo-300" />
                        : <Ban size={15} className="text-slate-400" />
                      }
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-200 truncate">
                        {trilha ? trilha.nome : 'Sem música'}
                      </p>
                      <p className="text-[11px] text-slate-500">
                        {trilha
                          ? `${MOOD_LABELS_PT[trilha.mood] || trilha.mood} - ${Math.round(trilha.duracao)}s`
                          : 'Toque para escolher uma trilha'}
                      </p>
                    </div>
                    <span className="text-[11px] font-medium text-indigo-300 px-2.5 py-1.5 rounded-md bg-indigo-600/10 border border-indigo-500/30">
                      {trilha ? 'Trocar' : 'Escolher'}
                    </span>
                  </button>

                  {/* Slider de volume - só quando há trilha selecionada */}
                  {trilha && (
                    <div className="mt-3 px-1">
                      <div className="flex items-center justify-between mb-1.5">
                        <p className="text-[10px] uppercase tracking-wide text-slate-500">
                          Volume da música
                        </p>
                        <span className="text-[11px] font-semibold text-indigo-300 tabular-nums">
                          {volumeMusica}%
                        </span>
                      </div>
                      <input
                        type="range"
                        min={0}
                        max={50}
                        step={1}
                        value={volumeMusica}
                        onChange={(e) => setVolumeMusica(Number(e.target.value))}
                        className="w-full h-1.5 accent-indigo-500 bg-white/10 rounded-full appearance-none cursor-pointer"
                        aria-label="Volume da música"
                      />
                      <div className="flex justify-between text-[9px] text-slate-500 mt-1">
                        <span>Mudo</span>
                        <span>Padrão (12%)</span>
                        <span>Alto (50%)</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Erro */}
            {erro && (
              <div className="bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-3 text-sm text-red-400">
                {erro}
              </div>
            )}

            {/* Botao gerar */}
            <button
              onClick={enviar}
              disabled={!arquivo || enviando || (aba === 'live' && segmentos.length === 0)}
              className="w-full py-4 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-40 disabled:cursor-not-allowed text-white font-bold rounded-xl transition-all flex items-center justify-center gap-2 text-base shadow-lg"
            >
              <Wand2 size={18} />
              {enviando ? 'Enviando...' : aba === 'live' ? `Gerar Reel com ${segmentos.length} trecho(s)` : 'Gerar Reel automaticamente'}
            </button>

            {/* Info */}
            <div className="grid grid-cols-3 gap-3 text-center">
              {[
                { label: 'Transcricao', desc: 'Whisper AI' },
                { label: 'B-roll', desc: 'Pexels API' },
                { label: 'Formato', desc: '1080x1920' },
              ].map(item => (
                <div key={item.label} className="bg-white/3 border border-white/8 rounded-xl p-3">
                  <p className="text-xs font-medium text-indigo-300">{item.label}</p>
                  <p className="text-[10px] text-slate-500 mt-0.5">{item.desc}</p>
                </div>
              ))}
            </div>
          </>
        )}
      </main>

      {/* Music Drawer */}
      <MusicDrawer
        open={drawerAberto}
        onClose={() => setDrawerAberto(false)}
        apiUrl={API_URL}
        selectedId={trilha?.id || null}
        onSelect={(t) => setTrilha(t)}
      />
    </div>
  )
}
