import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Activity } from "lucide-react";
import { getLiveTicker, type TickerEntry } from "@/lib/live-ticker.functions";
import { formatNaira } from "@/lib/format";

function relTime(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const s = Math.max(1, Math.floor(diff / 1000));
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

export function LiveTicker() {
  const fetchTicker = useServerFn(getLiveTicker);
  const { data } = useQuery({
    queryKey: ["live-ticker"],
    queryFn: () => fetchTicker(),
    refetchInterval: 15_000,
    staleTime: 5_000,
  });
  const items = (data ?? []) as TickerEntry[];
  if (!items.length) return null;
  // Duplicate for seamless loop
  const loop = [...items, ...items];

  return (
    <div className="relative overflow-hidden rounded-2xl border border-border/60 bg-card shadow-card">
      <div className="flex items-center gap-2 border-b border-border/60 px-3 py-2">
        <span className="relative flex h-2 w-2">
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
        </span>
        <Activity className="h-3.5 w-3.5 text-primary" />
        <div className="text-[11px] font-bold uppercase tracking-wider text-foreground">
          Billsline Live
        </div>
        <div className="ml-auto text-[10px] text-muted-foreground">Real-time</div>
      </div>
      <div className="group relative flex overflow-hidden py-2.5 [--ticker-duration:60s]">
        <div className="flex shrink-0 animate-[ticker_var(--ticker-duration)_linear_infinite] gap-6 pl-6 group-hover:[animation-play-state:paused]">
          {loop.map((e, i) => (
            <div key={i} className="flex items-center gap-2 whitespace-nowrap text-xs">
              <span className="grid h-6 w-6 place-items-center rounded-full bg-gradient-primary text-[10px] font-bold text-primary-foreground">
                {e.name.charAt(0).toUpperCase()}
              </span>
              <span className="font-semibold text-foreground">{e.name}</span>
              <span className="text-muted-foreground">{e.action}</span>
              <span className="rounded-md bg-emerald-500/10 px-1.5 py-0.5 font-mono text-[11px] font-bold text-emerald-600 dark:text-emerald-400">
                {formatNaira(Number(e.amount))}
              </span>
              <span className="text-[10px] text-muted-foreground">· {relTime(e.occurred_at)}</span>
              <span className="mx-1 h-1 w-1 rounded-full bg-border" />
            </div>
          ))}
        </div>
      </div>
      <style>{`@keyframes ticker { from { transform: translateX(0) } to { transform: translateX(-50%) } }`}</style>
    </div>
  );
}
