"use client";

import { useRef, useState, type CSSProperties } from "react";
import '@videojs/react/video/skin.css';
import { VideoPlayer, VideoSkin, Video } from '@videojs/react/video';
import { HlsJsVideo } from '@videojs/react/media/hlsjs-video';
import { AlertCircle, CheckCircle2, ExternalLink, RotateCcw, Volume2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { directVideoUrl, httpsUrl, timeLabel, type VideoInput } from "@/lib/arkvideo";

export function PreviewPlayer({ video, storageId, onDuration }: { video: VideoInput; storageId?: string; onDuration?: (duration: number) => void }) {
  const ref = useRef<HTMLVideoElement>(null);
  const lastStored = useRef(0);
  const [status, setStatus] = useState("Carregando metadados…");
  const [error, setError] = useState("");
  const [position, setPosition] = useState(0);
  const [resumeAt, setResumeAt] = useState<number | null>(null);
  const [unmuted, setUnmuted] = useState(false);
  const [storageNotice, setStorageNotice] = useState(false);
  const [attempt, setAttempt] = useState(0);
  const key = storageId ? `arkvideo:preview:${storageId}` : "";
  const ctaVisible = video.ctaEnabled && position >= video.ctaAt && !!video.ctaText && httpsUrl(video.ctaUrl);
  function persist(force = false) {
    const el = ref.current;
    if (!video.resume || !el || !key || (!force && Date.now() - lastStored.current < 5000)) return;
    lastStored.current = Date.now();
    try { localStorage.setItem(key, String(el.ended ? 0 : el.currentTime)); } catch { setStorageNotice(true); }
  }
  function metadata() {
    const el = ref.current;
    if (!el) return;
    setStatus("Metadados carregados. Pressione play para testar.");
    if (Number.isFinite(el.duration) && el.duration > 0) onDuration?.(Math.round(el.duration * 100) / 100);
    if (video.resume && key) {
      try {
        const saved = Number(localStorage.getItem(key));
        if (saved > 3 && Number.isFinite(saved) && saved < el.duration - 2) { el.pause(); setResumeAt(saved); }
      } catch { setStorageNotice(true); }
    }
  }
  function playbackError() {
    const code = ref.current?.error?.code;
    setStatus("");
    setError(code === 3 ? "O navegador não conseguiu decodificar a mídia. Confira o codec e o formato selecionado." : code === 4 ? "Fonte indisponível ou formato incompatível. Confira o link direto, o formato e a permissão CORS no host." : "Não foi possível reproduzir. Verifique a conexão, o CORS do host e se o token do link assinado ainda está válido. O navegador pode não informar a causa exata.");
  }
  async function start(time: number) {
    if (!ref.current) return;
    ref.current.currentTime = time;
    setPosition(time);
    setResumeAt(null);
    try { await ref.current.play(); } catch { setStatus("Pressione play para iniciar a reprodução."); }
  }
  const props = {
    ref, src: video.url, poster: video.poster && httpsUrl(video.poster) ? video.poster : undefined,
    className: "h-full w-full object-contain", playsInline: true, preload: "metadata" as const,
    autoPlay: video.autoplay, muted: video.autoplay && !unmuted, crossOrigin: "anonymous" as const,
    onLoadedMetadata: metadata,
    onPlay: () => { setError(""); setStatus("Reprodução iniciada com sucesso."); },
    onTimeUpdate: () => { setPosition(ref.current?.currentTime || 0); persist(); },
    onPause: () => { persist(true); },
    onEnded: () => { persist(true); setStatus("Reprodução concluída."); },
    onError: playbackError,
    onWaiting: () => setStatus("Aguardando dados do host…"),
    onPlaying: () => setStatus("Reprodução funcionando. Prévia sem coleta de métricas."),
  };
  if (!directVideoUrl(video.url)) return <p role="alert" className="rounded-xl border border-amber-500/25 bg-amber-500/5 p-4 text-sm text-amber-200">Informe um link direto HTTPS válido para testar a reprodução.</p>;
  return <div className="space-y-3">
    <div className="overflow-hidden rounded-xl border border-white/10 bg-black" style={{ "--media-accent-color": /^#[0-9a-f]{6}$/i.test(video.color) ? video.color : "#8b5cf6", "--media-accent-text-color": "#ffffff" } as CSSProperties}>
      <VideoPlayer key={`${video.url}:${video.format}:${attempt}`}>
        <VideoSkin className="aspect-video w-full">
          {video.format === "HLS" ? <HlsJsVideo {...props} /> : <Video {...props} />}
        </VideoSkin>
      </VideoPlayer>
    </div>
    {resumeAt !== null && <div className="flex flex-wrap items-center gap-3 rounded-lg border bg-secondary p-3 text-sm"><span className="mr-auto">Continuar de {timeLabel(resumeAt)}?</span><Button size="sm" variant="outline" onClick={() => start(0)}>Do início</Button><Button size="sm" onClick={() => start(resumeAt)}>Continuar</Button></div>}
    {video.autoplay && !unmuted && <Button size="sm" variant="outline" onClick={() => { if (ref.current) ref.current.muted = false; setUnmuted(true); }}><Volume2 size={16} />Ativar som</Button>}
    {ctaVisible && <div className="rounded-xl border border-violet-400/20 bg-violet-500/5 p-4 text-center"><a href={video.ctaUrl} target="_blank" rel="noopener noreferrer" className="inline-flex max-w-full items-center justify-center gap-2 rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground break-words">{video.ctaText}<ExternalLink className="size-4 shrink-0" /></a></div>}
    {video.brand && <p className="text-right text-xs text-muted-foreground">{video.brand}</p>}
    {error ? <div role="alert" className="space-y-3 rounded-xl border border-amber-400/20 bg-amber-400/5 p-4"><p className="flex gap-2 text-sm leading-relaxed text-amber-200"><AlertCircle className="mt-0.5 size-4 shrink-0" />{error}</p><Button variant="outline" size="sm" onClick={() => { setError(""); setStatus("Tentando novamente…"); setAttempt(v => v + 1); }}><RotateCcw size={14} />Tentar novamente</Button></div> : <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground"><CheckCircle2 className="size-3.5 text-emerald-400" />{status}</p>}
    {storageNotice && <p className="text-xs text-muted-foreground">O armazenamento deste navegador está bloqueado. A reprodução funciona, mas a posição não será lembrada.</p>}
  </div>;
}
