"use client";

import { useState, type FormEvent, type ReactNode } from "react";
import dynamic from "next/dynamic";
import { ArrowRight, Check, ExternalLink, Film, Globe2, Link2, Loader2, Palette, Play, Save } from "lucide-react";
import { toast } from "sonner";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { defaultVideo, directVideoUrl, videoSchema, type VideoInput, type VslVideo } from "@/lib/arkvideo";
import { saveVideo } from "@/app/actions";
import { VideoUpload } from "./video-upload";

export const Player = dynamic(() => import("./preview-player").then(m => m.PreviewPlayer), { ssr: false, loading: () => <div role="status" className="flex aspect-video items-center justify-center rounded-xl border bg-black text-sm text-muted-foreground"><Loader2 className="mr-2 size-4 animate-spin" />Carregando o player…</div> });
const selectClass = "h-10 w-full rounded-lg border border-input bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring";
export function Field({ id, label, hint, children }: { id: string; label: string; hint?: string; children: ReactNode }) {
  return <div className="space-y-2"><Label htmlFor={id} className="text-sm font-medium text-foreground/90">{label}</Label>{children}{hint && <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>}</div>;
}
function Toggle({ title, hint, checked, onChange }: { title: string; hint: string; checked: boolean; onChange: (v: boolean) => void }) {
  return <label className="flex cursor-pointer items-center justify-between gap-5 rounded-xl border bg-background/40 p-4"><span><span className="block text-sm font-medium">{title}</span><span className="mt-1 block text-xs leading-relaxed text-muted-foreground">{hint}</span></span><Switch aria-label={title} checked={checked} onCheckedChange={onChange} /></label>;
}
export function VideoEditor({ initial, onClose, onSaved, folders }: { initial?: VslVideo; onClose: () => void; onSaved: () => Promise<void>; folders: string[] }) {
  const [draft, setDraft] = useState<VideoInput>(initial ?? { ...defaultVideo });
  const [tab, setTab] = useState("video");
  const [busy, setBusy] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const [test, setTest] = useState<VideoInput | null>(null);
  const update = <K extends keyof VideoInput>(key: K, value: VideoInput[K]) => setDraft(v => ({ ...v, [key]: value }));
  async function submit(e: FormEvent) {
    e.preventDefault();
    setError("");
    const parsed = videoSchema.safeParse(draft);
    if (!parsed.success) { setError(parsed.error.issues[0].message); return; }
    setBusy(true);
    try {
      const result = await saveVideo(parsed.data, initial?.id);
      if (!result.ok) { setError(result.error); return; }
      toast.success(initial ? "Alterações salvas." : "Vídeo cadastrado na biblioteca.");
      await onSaved(); onClose();
    } catch { setError("Não foi possível concluir o cadastro. Verifique sua conexão e tente novamente."); }
    finally { setBusy(false); }
  }
  return <Dialog open onOpenChange={open => { if (!open && !busy && !uploading) onClose(); }}><DialogContent className="max-h-[92dvh] gap-0 overflow-y-auto border-white/10 bg-card p-0 sm:max-w-3xl">
    <DialogHeader className="border-b px-6 py-5"><div className="mb-2 flex items-center gap-2 text-xs font-medium uppercase tracking-widest text-violet-400"><Film size={14} />Sua biblioteca VSL</div><DialogTitle className="text-xl">{initial ? "Editar vídeo" : "Novo vídeo"}</DialogTitle><DialogDescription>Envie um MP4 ao cPanel ou conecte um link externo. A mídia nunca é enviada à Teable.</DialogDescription></DialogHeader>
    <form onSubmit={submit}>
      <Tabs value={tab} onValueChange={value => { if (!uploading) setTab(value); }} className="gap-0">
        <div className="overflow-x-auto border-b px-6 py-4"><TabsList className="h-10 w-full min-w-[380px] bg-secondary"><TabsTrigger value="video"><Film className="size-3.5" />Vídeo</TabsTrigger><TabsTrigger value="player"><Palette className="size-3.5" />Player</TabsTrigger><TabsTrigger value="cta"><ArrowRight className="size-3.5" />CTA</TabsTrigger><TabsTrigger value="domains"><Globe2 className="size-3.5" />Domínios</TabsTrigger></TabsList></div>
        <div className="px-6 py-5">
          <TabsContent value="video" className="mt-0 space-y-5">
            <Field id="title" label="Título do vídeo *"><Input id="title" autoFocus maxLength={180} value={draft.title} onChange={e => update("title", e.target.value)} placeholder="Dê um nome à sua VSL" /></Field>
            <VideoUpload onBusyChange={setUploading} onUploaded={(url, name) => { setDraft(v => ({ ...v, url, format: "MP4", title: v.title || name.slice(0, 180) })); }} />
            <Field id="url" label="URL direta do vídeo *" hint="MP4 ou HLS via HTTPS. URLs assinadas e links sem extensão são aceitos. Páginas do YouTube, Drive e Vimeo não são links diretos."><div className="relative"><Link2 className="absolute top-3 left-3 size-4 text-muted-foreground" /><Input id="url" type="url" className="pl-9" value={draft.url} onChange={e => update("url", e.target.value)} placeholder="Cole o link HTTPS do arquivo" /></div></Field>
            <div className="grid grid-cols-2 gap-4"><Field id="format" label="Formato"><select id="format" className={selectClass} value={draft.format} onChange={e => update("format", e.target.value as VideoInput["format"])}><option>MP4</option><option>HLS</option></select></Field><Field id="status" label="Status"><select id="status" className={selectClass} value={draft.status} onChange={e => update("status", e.target.value as VideoInput["status"])}><option>Rascunho</option><option>Ativo</option><option>Pausado</option></select></Field></div>
            <div className="grid gap-4 sm:grid-cols-2"><Field id="folder" label="Pasta" hint="Digite uma nova pasta ou escolha uma existente."><Input id="folder" list="folder-options" value={draft.folder} onChange={e => update("folder", e.target.value)} placeholder="Sem pasta" /><datalist id="folder-options">{folders.map(f => <option key={f} value={f} />)}</datalist></Field><Field id="duration" label="Duração em segundos" hint="Preenchida ao carregar os metadados no teste."><Input id="duration" type="number" min={0} max={86400} step="0.01" value={draft.duration || ""} onChange={e => update("duration", Number(e.target.value))} placeholder="Ainda não identificada" /></Field></div>
            <Field id="description" label="Descrição"><Textarea id="description" value={draft.description} onChange={e => update("description", e.target.value)} placeholder="Anotações para organizar esta VSL…" rows={2} /></Field>
            <div className="space-y-3 rounded-xl border bg-background/40 p-4"><div className="flex flex-wrap items-center justify-between gap-3"><div><p className="text-sm font-medium">Confira o seu link</p><p className="mt-1 text-xs text-muted-foreground">O teste ocorre no navegador, sem registrar métricas.</p></div><Button type="button" variant="outline" size="sm" onClick={() => { if (!directVideoUrl(draft.url.trim())) { setError("Informe um link direto HTTPS válido antes de testar."); return; } setError(""); setTest({ ...draft, url: draft.url.trim() }); }}><Play size={14} />Testar reprodução</Button></div><p className="text-xs leading-relaxed text-muted-foreground">O host deve permitir CORS para este app e para o player publicado. Links assinados precisam estar válidos.</p>{test && <Player key={`${test.url}:${test.format}`} video={test} storageId={initial?.publicId} onDuration={d => { if (draft.url.trim() === test.url) update("duration", d); }} />}</div>
          </TabsContent>
          <TabsContent value="player" className="mt-0 space-y-5">
            <Field id="poster" label="URL da capa" hint="Uma imagem HTTPS no seu host. Não fazemos upload para a Teable."><Input id="poster" value={draft.poster} onChange={e => update("poster", e.target.value)} placeholder="Cole o link HTTPS da imagem" /></Field>
            <div className="grid gap-4 sm:grid-cols-2"><Field id="color" label="Cor do player"><div className="flex gap-2"><input id="color" aria-label="Cor do player" type="color" value={draft.color} onChange={e => update("color", e.target.value)} className="h-10 w-12 cursor-pointer rounded-lg border bg-background p-1" /><Input aria-label="Cor hexadecimal" value={draft.color} onChange={e => update("color", e.target.value)} maxLength={7} /></div></Field><Field id="brand" label="Marca"><Input id="brand" value={draft.brand} onChange={e => update("brand", e.target.value)} placeholder="Nome exibido abaixo do player" /></Field></div>
            <Toggle title="Autoplay sem som" hint="O navegador pode bloquear o início automático. O visitante ativa o som por interação." checked={draft.autoplay} onChange={v => update("autoplay", v)} />
            <Toggle title="Retomar reprodução" hint="Oferece continuar de onde parou, quando o navegador permite armazenamento local." checked={draft.resume} onChange={v => update("resume", v)} />
            <p className="rounded-xl border border-violet-500/15 bg-violet-500/5 p-4 text-xs leading-relaxed text-muted-foreground">Video.js 10.1.0 · Controles acessíveis · MP4 e HLS<br />A prévia permite pausar, avançar e sair livremente.</p>
          </TabsContent>
          <TabsContent value="cta" className="mt-0 space-y-5"><Toggle title="Ativar chamada para ação" hint="O botão aparece abaixo do vídeo, sem cobrir os controles." checked={draft.ctaEnabled} onChange={v => update("ctaEnabled", v)} />
            <Field id="ctaAt" label="Exibir a partir de (segundos)"><Input id="ctaAt" type="number" min={0} step="0.1" value={draft.ctaAt} onChange={e => update("ctaAt", Number(e.target.value))} /></Field>
            <Field id="ctaText" label="Texto do botão"><Input id="ctaText" value={draft.ctaText} onChange={e => update("ctaText", e.target.value)} placeholder="Texto da sua chamada para ação" /></Field>
            <Field id="ctaUrl" label="Link do CTA" hint="HTTPS obrigatório. Abre em nova aba com noopener e noreferrer."><Input id="ctaUrl" value={draft.ctaUrl} onChange={e => update("ctaUrl", e.target.value)} placeholder="Cole o link HTTPS de destino" /></Field>
            {draft.ctaText && <div className="rounded-xl border border-dashed p-6 text-center"><span className="mb-3 block text-xs text-muted-foreground">Aparência do botão</span><span className="inline-flex items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium">{draft.ctaText}<ExternalLink size={14} /></span></div>}
          </TabsContent>
          <TabsContent value="domains" className="mt-0 space-y-5"><div className="flex size-11 items-center justify-center rounded-xl bg-violet-500/10 text-violet-400"><Globe2 size={22} /></div><Field id="domains" label="Origens autorizadas" hint="Uma origem HTTPS por linha. Sem caminhos, parâmetros ou curingas. Deixe vazio para não restringir a incorporação."><Textarea id="domains" rows={6} value={draft.domains} onChange={e => update("domains", e.target.value)} placeholder="Cole as origens HTTPS das suas páginas" className="font-mono text-xs" /></Field><div className="space-y-2 rounded-xl border bg-background/40 p-4 text-xs leading-relaxed text-muted-foreground"><p>O app player deve aplicar essas origens no cabeçalho CSP frame-ancestors. Esta configuração controla onde o player pode ser incorporado.</p><p>Isso não protege o arquivo no host, não é DRM e não impede o download de mídia pública. Links assinados vencem no prazo definido pelo provedor.</p></div></TabsContent>
        </div>
      </Tabs>
      <div className="sticky bottom-0 space-y-3 border-t bg-card px-6 py-4">{error && <p role="alert" className="rounded-lg bg-red-400/10 p-3 text-sm text-red-300">{error}</p>}<div className="flex items-center justify-between gap-3"><span className="hidden items-center gap-1.5 text-xs text-muted-foreground sm:flex"><Check size={13} />Mídia no seu host, nunca na Teable</span><div className="ml-auto flex gap-2"><Button type="button" variant="outline" disabled={busy || uploading} onClick={onClose}>Cancelar</Button><Button type="submit" disabled={busy || uploading}>{busy ? <Loader2 className="size-4 animate-spin" /> : <Save size={15} />}{busy ? "Salvando…" : initial ? "Salvar alterações" : "Cadastrar vídeo"}</Button></div></div></div>
    </form>
  </DialogContent></Dialog>;
}
