"use client";

import { useState } from "react";
import { ArrowRight, CheckCircle2, Code2, Copy, Globe2, Info, Link2, Loader2, LockKeyhole, Radio, Save } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { embedCode, httpsOrigin, type VslVideo } from "@/lib/arkvideo";
import { savePlayerOrigin } from "@/app/actions";

export async function copyText(text: string) {
  try { await navigator.clipboard.writeText(text); toast.success("Código de incorporação copiado."); }
  catch { toast.error("O navegador bloqueou a cópia. Selecione e copie o código manualmente."); }
}
export function EmbedView({ videos, playerOrigin, settingsError, onSaved, onPreview, initialVideoId }: { videos: VslVideo[]; playerOrigin: string | null; settingsError: string | null; onSaved: () => Promise<void>; onPreview: (v: VslVideo) => void; initialVideoId?: string }) {
  const [origin, setOrigin] = useState(playerOrigin || "");
  const [videoId, setVideoId] = useState(initialVideoId || videos[0]?.id || "");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const selected = videos.find(v => v.id === videoId);
  const configured = !!playerOrigin && httpsOrigin(playerOrigin);
  const code = selected && configured ? embedCode(playerOrigin, selected) : "";
  async function save() {
    setBusy(true); setError("");
    try {
      const result = await savePlayerOrigin(origin);
      if (!result.ok) { setError(result.error); return; }
      toast.success(origin.trim() ? "Origem pública do player salva." : "Origem removida. Integração aguardando publicação.");
      await onSaved();
    } catch { setError("Não foi possível salvar a configuração. Tente novamente."); }
    finally { setBusy(false); }
  }
  return <div className="space-y-7">
    <div><div className="mb-2 text-xs font-medium uppercase tracking-[0.16em] text-violet-400">Do seu host para sua página</div><h1 className="text-3xl font-semibold tracking-tight">Como incorporar</h1><p className="mt-2 text-sm text-muted-foreground">Conecte o player público e leve suas VSLs para qualquer página autorizada.</p></div>
    <div className={`flex items-start gap-4 rounded-xl border p-5 ${configured ? "border-emerald-400/20 bg-emerald-400/5" : "border-violet-400/20 bg-violet-500/5"}`}><div className={`flex size-10 shrink-0 items-center justify-center rounded-lg ${configured ? "bg-emerald-400/10 text-emerald-400" : "bg-violet-500/15 text-violet-400"}`}>{configured ? <CheckCircle2 size={20} /> : <Radio size={20} />}</div><div><h2 className="text-sm font-medium">{configured ? "Origem do player configurada" : "Integração aguardando publicação do player"}</h2><p className="mt-1.5 max-w-3xl text-xs leading-relaxed text-muted-foreground">{configured ? "Os códigos abaixo usam a origem salva. Confirme que o pacote cPanel está em produção nessa origem e está conectado às mesmas tabelas." : "Este pacote inclui o player público em /embed. Depois de instalar com HTTPS, salve abaixo a origem real do seu domínio cPanel."}</p></div></div>
    <div className="grid gap-6 xl:grid-cols-[1.1fr_1fr]">
      <div className="space-y-6">
        <section className="rounded-xl border bg-card p-6"><div className="mb-5 flex items-center gap-3"><span className="flex size-7 items-center justify-center rounded-full border border-violet-400/25 bg-violet-500/10 text-xs font-semibold text-violet-300">1</span><h2 className="font-medium">Conecte o seu player</h2></div><Label htmlFor="player-origin">Origem HTTPS do player público</Label><div className="relative mt-2"><Globe2 className="absolute top-3 left-3 size-4 text-muted-foreground" /><Input id="player-origin" value={origin} onChange={e => setOrigin(e.target.value)} className="pl-9" placeholder="Cole a origem real após publicar o player" /></div><p className="mt-2 text-xs leading-relaxed text-muted-foreground">Apenas protocolo e domínio, com porta se necessário. Sem /embed, caminhos ou parâmetros.</p>{(error || settingsError) && <p role="alert" className="mt-3 text-sm text-red-300">{error || settingsError}</p>}<Button className="mt-5" size="sm" disabled={busy || !!settingsError} onClick={save}>{busy ? <Loader2 className="size-4 animate-spin" /> : <Save size={14} />}{busy ? "Salvando…" : "Salvar origem"}</Button></section>
        <section className="rounded-xl border bg-card p-6"><div className="mb-5 flex items-center gap-3"><span className="flex size-7 items-center justify-center rounded-full border border-violet-400/25 bg-violet-500/10 text-xs font-semibold text-violet-300">2</span><h2 className="font-medium">Escolha a VSL</h2></div><Label htmlFor="embed-video">Vídeo da biblioteca</Label><select id="embed-video" value={videoId} onChange={e => setVideoId(e.target.value)} className="mt-2 h-10 w-full rounded-lg border bg-background px-3 text-sm" disabled={!videos.length}><option value="">{videos.length ? "Selecione um vídeo" : "Cadastre seu primeiro vídeo"}</option>{videos.map(v => <option key={v.id} value={v.id}>{v.title} · {v.status}</option>)}</select>{selected && <div className="mt-4 flex items-center justify-between gap-2"><span className="text-xs text-muted-foreground">{selected.status === "Ativo" ? "Vídeo ativo para o player público" : "Ative o vídeo para disponibilizar no player"}</span><Button size="sm" variant="ghost" onClick={() => onPreview(selected)}>Abrir prévia<ArrowRight size={14} /></Button></div>}</section>
      </div>
      <section className="flex flex-col rounded-xl border bg-card p-6"><div className="mb-5 flex items-center gap-3"><span className="flex size-7 items-center justify-center rounded-full border border-violet-400/25 bg-violet-500/10 text-xs font-semibold text-violet-300">3</span><h2 className="font-medium">Copie e incorpore</h2></div><p className="text-sm leading-relaxed text-muted-foreground">Cole o código em um bloco HTML da sua página. O iframe se ajusta à largura disponível.</p><div className="my-5 flex min-h-52 flex-1 flex-col justify-center rounded-lg border border-white/5 bg-background p-5">{code ? <textarea aria-label="Código de incorporação" readOnly value={code} className="min-h-44 w-full resize-y bg-transparent font-mono text-xs leading-6 text-violet-200 outline-none" onFocus={e => e.currentTarget.select()} /> : <div className="text-center"><Code2 className="mx-auto mb-3 size-8 text-muted-foreground/40" /><p className="text-sm text-muted-foreground">{!configured ? "Aguardando a origem pública do player" : "Selecione um vídeo para gerar o código"}</p><p className="mt-2 text-xs text-muted-foreground/70">Nenhuma URL provisória será gerada.</p></div>}</div><Button disabled={!code || selected?.status !== "Ativo"} onClick={() => copyText(code)}><Copy size={15} />Copiar código de incorporação</Button><p className="mt-3 text-center text-[11px] text-muted-foreground">Autoplay · Tela cheia · Picture-in-picture</p></section>
    </div>
    <div className="grid gap-5 md:grid-cols-3">{[
      { icon: Link2, title: "Mídia no seu host", text: "Use links diretos HTTPS de MP4 ou HLS. O host deve permitir CORS para o player. Nenhum vídeo é copiado para a Teable." },
      { icon: LockKeyhole, title: "Controle de incorporação", text: "O player incluído aplica as origens autorizadas com CSP frame-ancestors. Referrer sozinho não protege a incorporação." },
      { icon: Info, title: "Transparência por padrão", text: "Não é DRM e não impede download de mídia pública. Links assinados vencem conforme o provedor. A prévia não gera métricas." },
    ].map(item => <div key={item.title} className="rounded-xl border bg-card/40 p-5"><item.icon size={19} className="mb-4 text-violet-400" /><h3 className="text-sm font-medium">{item.title}</h3><p className="mt-2 text-xs leading-relaxed text-muted-foreground">{item.text}</p></div>)}</div>
    <details className="rounded-xl border bg-card p-5"><summary className="cursor-pointer text-sm font-medium">Compatibilidade das métricas com o app player</summary><div className="mt-4 space-y-3 text-xs leading-relaxed text-muted-foreground"><p>O painel lê Sessões VSL, excluindo Prévia=true. O player incluído valida e grava sessões, tempo assistido e eventos únicos por endpoints públicos limitados. Os envios de arquivos e a administração exigem login.</p><p>O painel lê os buckets de 5 segundos gravados pelo ArkVideo Player e também aceita intervalos efetivamente vistos no formato abaixo. Para buckets, a duração vem do cadastro do vídeo; para intervalos, ela pode vir do JSON ou do cadastro. Dados ausentes ou incompatíveis são sinalizados, sem inferir retenção pela posição final.</p><code className="block overflow-x-auto rounded-lg bg-background p-3 text-violet-200">{'{"version":1,"duration":<segundos>,"intervals":[[<início>,<fim>]]}'}</code><p>O denominador da retenção é o número de sessões iniciadas com intervalos válidos; cada sessão conta uma vez por faixa, mesmo após rever o trecho.</p></div></details>
  </div>;
}
