"use client";

import { useCallback, useEffect, useState } from "react";
import { BarChart3, Download, Eye, MousePointerClick, Play, RefreshCw, Timer, TrendingUp } from "lucide-react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { Button } from "@/components/ui/button";
import { getMetrics } from "@/app/actions";
import { csvCell, type Metrics, type VslVideo } from "@/lib/arkvideo";

const num = (n: number) => n.toLocaleString("pt-BR", { maximumFractionDigits: 1 });
const percent = (n: number, d: number) => `${num(d ? n / d * 100 : 0)}%`;
const tooltipStyle = { background: "#1b1b23", border: "1px solid #30303c", borderRadius: 10, color: "#eee" };
export function MetricsView({ videos, initialVideoId = "" }: { videos: VslVideo[]; initialVideoId?: string }) {
  const [days, setDays] = useState(30);
  const [videoId, setVideoId] = useState(initialVideoId);
  const [data, setData] = useState<Metrics | null>(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const [refresh, setRefresh] = useState(0);
  useEffect(() => {
    let current = true;
    setLoading(true); setError(""); setData(null);
    getMetrics(days, videoId).then(result => {
      if (!current) return;
      if (result.ok) setData(result.data); else setError(result.error);
    }).catch(() => { if (current) setError("Não foi possível carregar as métricas. Verifique a conexão e tente novamente."); }).finally(() => { if (current) setLoading(false); });
    return () => { current = false; };
  }, [days, videoId, refresh]);
  const exportCsv = useCallback(() => {
    if (!data) return;
    const header = ["Vídeo", "Sessões", "Plays", "Taxa de play (%)", "Conclusões", "Taxa de conclusão (%)", "Segundos assistidos", "CTAs exibidos", "Cliques no CTA", "CTR do CTA (%)"];
    const rows = data.rows.map(r => [r.title, r.sessions, r.plays, r.sessions ? (r.plays / r.sessions * 100).toFixed(2) : 0, r.completed, r.plays ? (r.completed / r.plays * 100).toFixed(2) : 0, r.watched.toFixed(2), r.ctaShown, r.ctaClicked, r.ctaShown ? (r.ctaClicked / r.ctaShown * 100).toFixed(2) : 0]);
    const content = "\ufeff" + [header, ...rows].map(row => row.map(csvCell).join(";")).join("\r\n");
    const url = URL.createObjectURL(new Blob([content], { type: "text/csv;charset=utf-8;" }));
    const a = document.createElement("a"); a.href = url; a.download = `arkvideo-metricas-${days}dias-${new Date().toISOString().slice(0, 10)}.csv`; a.click(); URL.revokeObjectURL(url);
  }, [data, days]);
  const cards = data ? [
    { title: "Plays", value: num(data.plays), detail: `${num(data.sessions)} sessões carregadas`, icon: Play },
    { title: "Taxa de play", value: percent(data.plays, data.sessions), detail: "Plays / sessões", icon: TrendingUp },
    { title: "Taxa de conclusão", value: percent(data.completed, data.plays), detail: `${num(data.completed)} conclusões / plays`, icon: Eye },
    { title: "Tempo assistido", value: `${num(data.watched)} s`, detail: "Somente tempo reproduzido", icon: Timer },
    { title: "CTR do CTA", value: percent(data.ctaClicked, data.ctaShown), detail: `${num(data.ctaClicked)} cliques / ${num(data.ctaShown)} exibições`, icon: MousePointerClick },
  ] : [];
  return <div className="space-y-7">
    <div className="flex flex-wrap items-start justify-between gap-4"><div><div className="mb-2 text-xs font-medium uppercase tracking-[0.16em] text-violet-400">Entenda sua audiência</div><h1 className="text-3xl font-semibold tracking-tight">Métricas</h1><p className="mt-2 text-sm text-muted-foreground">{videoId ? `Resultados de ${videos.find(video => video.id === videoId)?.title || "vídeo selecionado"}.` : "Cada reprodução conta. Acompanhe o desempenho das suas VSLs."}</p></div><Button variant="outline" onClick={exportCsv} disabled={!data || loading}><Download size={15} />Exportar CSV</Button></div>
    <div className="flex flex-wrap items-center justify-between gap-3"><div className="flex items-center rounded-lg border bg-card p-1">{[7, 30, 90].map(d => <button key={d} onClick={() => setDays(d)} aria-pressed={d === days} className={`rounded-md px-4 py-2 text-xs font-medium transition-colors ${days === d ? "bg-violet-500/15 text-violet-300" : "text-muted-foreground hover:text-foreground"}`}>{d} dias</button>)}</div><div className="flex items-center gap-2"><select aria-label="Filtrar métricas por vídeo" value={videoId} onChange={e => setVideoId(e.target.value)} className="h-10 max-w-64 rounded-lg border bg-card px-3 text-sm"><option value="">Todos os vídeos</option>{videos.map(v => <option key={v.id} value={v.id}>{v.title}</option>)}</select><Button size="icon" variant="outline" aria-label="Atualizar métricas" onClick={() => setRefresh(v => v + 1)} disabled={loading}><RefreshCw size={15} className={loading ? "animate-spin" : ""} /></Button></div></div>
    {error && <div role="alert" className="rounded-xl border border-red-400/20 bg-red-400/5 p-5"><p className="mb-3 text-sm text-red-300">{error}</p><Button variant="outline" size="sm" onClick={() => setRefresh(v => v + 1)}>Tentar novamente</Button></div>}
    {loading && <div role="status" aria-label="Carregando métricas" className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">{Array.from({ length: 5 }, (_, i) => <div key={i} className="h-36 animate-pulse rounded-xl border bg-card" />)}<span className="sr-only">Carregando métricas reais…</span></div>}
    {data && !loading && <><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">{cards.map(c => <div key={c.title} className="rounded-xl border bg-card p-5"><div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">{c.title}<c.icon size={15} className="text-violet-400" /></div><p className="mt-5 text-2xl font-semibold tracking-tight">{c.value}</p><p className="mt-2 text-[11px] text-muted-foreground">{c.detail}</p></div>)}</div>
    {!data.sessions ? <div className="flex min-h-72 flex-col items-center justify-center rounded-2xl border border-dashed bg-card/40 p-8 text-center"><div className="mb-5 flex size-14 items-center justify-center rounded-2xl border border-violet-400/20 bg-violet-500/10 text-violet-400"><BarChart3 size={25} /></div><h2 className="text-lg font-medium">Seus resultados começam com o primeiro play</h2><p className="mt-2 max-w-md text-sm leading-relaxed text-muted-foreground">Ainda não há sessões de produção neste período. Os dados aparecerão quando o app player registrar reproduções reais.</p><span className="mt-5 rounded-full border px-3 py-1 text-[11px] text-muted-foreground">Prévias internas não contam nas métricas</span></div> : <div className="grid gap-5 xl:grid-cols-2">
      <section className="rounded-xl border bg-card p-5"><h2 className="font-medium">Plays ao longo do período</h2><p className="mt-1 text-xs text-muted-foreground">Sessões que iniciaram a reprodução · horário de Brasília</p><div className="mt-6 h-60" role="img" aria-label="Gráfico de plays por dia"><ResponsiveContainer width="100%" height="100%"><AreaChart data={data.daily}><CartesianGrid vertical={false} stroke="#282830" strokeDasharray="3 3" /><XAxis dataKey="date" tickFormatter={v => `${String(v).slice(8)}/${String(v).slice(5, 7)}`} tick={{ fontSize: 11, fill: "#92929e" }} axisLine={false} tickLine={false} /><YAxis allowDecimals={false} width={30} tick={{ fontSize: 11, fill: "#92929e" }} axisLine={false} tickLine={false} /><Tooltip contentStyle={tooltipStyle} labelFormatter={v => String(v).split("-").reverse().join("/")} /><Area dataKey="plays" name="Plays" type="linear" stroke="#a78bfa" fill="#8b5cf6" fillOpacity={0.08} strokeWidth={2} /></AreaChart></ResponsiveContainer></div></section>
      <section className="rounded-xl border bg-card p-5"><h2 className="font-medium">Retenção por trecho</h2><p className="mt-1 text-xs text-muted-foreground">Sessões com reprodução registrada por faixa · resolução de 5 s no player</p>{data.retentionSessions ? <div className="mt-6 h-60" role="img" aria-label="Gráfico de retenção nos intervalos assistidos"><ResponsiveContainer width="100%" height="100%"><BarChart data={data.retention.map((count, i) => ({ range: `${i * 10}–${(i + 1) * 10}%`, percent: Math.round(count / data.retentionSessions * 1000) / 10 }))}><CartesianGrid vertical={false} stroke="#282830" strokeDasharray="3 3" /><XAxis dataKey="range" tick={{ fontSize: 9, fill: "#92929e" }} axisLine={false} tickLine={false} /><YAxis domain={[0, 100]} unit="%" width={35} tick={{ fontSize: 11, fill: "#92929e" }} axisLine={false} tickLine={false} /><Tooltip contentStyle={tooltipStyle} /><Bar dataKey="percent" name="Retenção (%)" fill="#8b5cf6" radius={[4, 4, 0, 0]} /></BarChart></ResponsiveContainer></div> : <div className="flex h-60 items-center justify-center text-center text-sm text-muted-foreground">Sem intervalos de retenção compatíveis neste período.</div>}{data.retentionUnavailable > 0 && <p className="mt-2 text-xs text-amber-300">{data.retentionUnavailable} sessões sem intervalos ou duração válidos não entram na retenção.</p>}</section>
    </div>}
    <section className="overflow-hidden rounded-xl border bg-card"><div className="border-b px-5 py-4"><h2 className="text-sm font-medium">Desempenho por vídeo</h2></div><div className="overflow-x-auto"><table className="w-full text-left text-xs"><thead className="bg-white/[0.015] text-muted-foreground"><tr>{["Vídeo", "Plays", "Taxa de play", "Conclusão", "Tempo assistido", "CTR do CTA"].map(h => <th key={h} className="whitespace-nowrap px-5 py-3 font-medium">{h}</th>)}</tr></thead><tbody>{data.rows.map(r => <tr key={r.id} className="border-t"><td className="min-w-44 px-5 py-4 font-medium">{r.title}</td><td className="px-5">{num(r.plays)}</td><td className="px-5">{percent(r.plays, r.sessions)}</td><td className="px-5">{percent(r.completed, r.plays)}</td><td className="whitespace-nowrap px-5">{num(r.watched)} s</td><td className="px-5">{percent(r.ctaClicked, r.ctaShown)}</td></tr>)}{!data.rows.length && <tr><td colSpan={6} className="px-5 py-10 text-center text-muted-foreground">Nenhum dado de produção para os filtros selecionados.</td></tr>}</tbody></table></div></section>
    <p className="text-xs leading-relaxed text-muted-foreground">Dados agregados no servidor, atualizados em até 30 segundos. Taxa de play = plays / sessões; conclusão = conclusões / plays; CTR = cliques / CTAs exibidos. As prévias são excluídas.</p></>}
  </div>;
}
