"use client";

/**
 * Admin → Activity Feed — premium operations-center surface.
 *
 * "Right Now" hero panel + filter chips + connected-timeline
 * feed with category icons + colored dots on a vertical rail.
 * Auto-polls every 10s on page 1 (paused on background tabs).
 */

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Activity, X, Loader2, ChevronLeft, ChevronRight, Download,
  Users as UsersIcon, Globe, Clock, Eye, FileText, Shield, Sparkles,
  Plug, Settings as SettingsIcon, Lock, AlertTriangle, RefreshCw, Wrench,
} from "lucide-react";
import Link from "next/link";
import {
  PageHeader, Card, CardHeader, EmptyState, Avatar, Skel,
} from "@/components/admin";

type Category = "navigation" | "search" | "audit" | "report" | "integration" | "content" | "ai" | "export" | "settings" | "auth" | "admin" | "seo" | "technical";

interface ActivityRow {
  id: string;
  action: string;
  category: string;
  metadata: unknown;
  timestamp: string;
  user: { id: string; name: string | null; email: string | null; image: string | null } | null;
  brand: { id: string; name: string | null; domain: string | null } | null;
}

interface Feed {
  rows: ActivityRow[];
  total: number; page: number; limit: number; hasMore: boolean;
  rightNow: { usersOnline: number; activeBrands: number; eventsPerMinute: number };
}

const POLL_MS = 10_000;

const CATEGORY_META: Record<Category, { label: string; chip: string; dot: string; icon: typeof Eye }> = {
  navigation:  { label: "Navigation",  chip: "bg-blue-50 text-blue-700",       dot: "bg-blue-500",    icon: Eye },
  search:      { label: "Search",      chip: "bg-cyan-50 text-cyan-700",       dot: "bg-cyan-500",    icon: Eye },
  audit:       { label: "Audit",       chip: "bg-orange-50 text-orange-700",   dot: "bg-orange-500",  icon: Shield },
  report:      { label: "Report",      chip: "bg-violet-50 text-violet-700",   dot: "bg-violet-500",  icon: FileText },
  integration: { label: "Integration", chip: "bg-sky-50 text-sky-700",         dot: "bg-sky-500",     icon: Plug },
  content:     { label: "Content",     chip: "bg-emerald-50 text-emerald-700", dot: "bg-emerald-500", icon: FileText },
  ai:          { label: "AI",          chip: "bg-purple-50 text-purple-700",   dot: "bg-purple-500",  icon: Sparkles },
  export:      { label: "Export",      chip: "bg-amber-50 text-amber-700",     dot: "bg-amber-500",   icon: Download },
  settings:    { label: "Settings",    chip: "bg-slate-100 text-slate-600",    dot: "bg-slate-400",   icon: SettingsIcon },
  auth:        { label: "Auth",        chip: "bg-indigo-50 text-indigo-700",   dot: "bg-indigo-500",  icon: Lock },
  admin:       { label: "Admin",       chip: "bg-rose-50 text-rose-700",       dot: "bg-rose-500",    icon: AlertTriangle },
  seo:         { label: "SEO",         chip: "bg-lime-50 text-lime-700",       dot: "bg-lime-500",    icon: Globe },
  technical:   { label: "Technical",   chip: "bg-teal-50 text-teal-700",       dot: "bg-teal-500",    icon: Wrench },
};

const FILTER_CHIPS: Array<{ id: string; label: string }> = [
  { id: "",            label: "All" },
  { id: "navigation",  label: "Navigation" },
  { id: "content",     label: "Content" },
  { id: "seo",         label: "SEO" },
  { id: "technical",   label: "Technical" },
  { id: "audit",       label: "Audit" },
  { id: "ai",          label: "AI" },
  { id: "report",      label: "Report" },
  { id: "settings",    label: "Settings" },
  { id: "admin",       label: "Admin" },
];

function formatTime(s: string): string {
  try {
    const d = new Date(s);
    const sec = Math.floor((Date.now() - d.getTime()) / 1000);
    if (sec < 10) return "just now";
    if (sec < 60) return `${sec}s ago`;
    if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
    if (sec < 86_400) return `${Math.floor(sec / 3600)}h ago`;
    return d.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
  } catch { return s; }
}

export default function AdminActivityPage() {
  const [categoryFilter, setCategoryFilter] = useState("");
  const [page, setPage] = useState(1);
  const [feed, setFeed] = useState<Feed | null>(null);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<ActivityRow | null>(null);
  const [livePoll, setLivePoll] = useState(true);

  const buildParams = useCallback(() => {
    const params = new URLSearchParams();
    if (categoryFilter) params.set("category", categoryFilter);
    params.set("page", String(page));
    return params;
  }, [categoryFilter, page]);

  const refresh = useCallback(async () => {
    const params = buildParams();
    const res = await fetch(`/api/admin/activity?${params.toString()}`);
    if (res.ok) setFeed(await res.json());
    setLoading(false);
  }, [buildParams]);

  useEffect(() => {
    setLoading(true);
    const handle = setTimeout(refresh, 250);
    return () => clearTimeout(handle);
  }, [refresh]);

  useEffect(() => {
    if (!livePoll) return;
    const tick = () => {
      if (typeof document !== "undefined" && document.hidden) return;
      if (page === 1) refresh();
    };
    const id = setInterval(tick, POLL_MS);
    return () => clearInterval(id);
  }, [livePoll, refresh, page]);

  const totalPages = useMemo(() => feed ? Math.max(1, Math.ceil(feed.total / feed.limit)) : 1, [feed]);

  function downloadCsv() {
    if (!feed) return;
    const header = ["timestamp", "user", "brand", "category", "action", "metadata"];
    const rows = feed.rows.map((r) => [
      r.timestamp, r.user?.email ?? r.user?.name ?? "",
      r.brand?.domain ?? r.brand?.name ?? "",
      r.category, r.action, JSON.stringify(r.metadata ?? {}),
    ].map((c) => `"${String(c).replace(/"/g, '""')}"`).join(","));
    const csv = [header.join(","), ...rows].join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `activity-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6 transition-opacity duration-200">
      <PageHeader
        title="Activity"
        subtitle={feed ? `${feed.total.toLocaleString()} matching events across the platform` : "Loading…"}
        icon={Activity}
        actions={
          <>
            <button
              onClick={() => setLivePoll((v) => !v)}
              className={`inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold rounded-lg border transition-colors ${
                livePoll
                  ? "bg-emerald-50 border-emerald-200 text-emerald-700"
                  : "bg-white border-slate-200 text-slate-600"
              }`}
            >
              <span className={`w-1.5 h-1.5 rounded-full ${livePoll ? "bg-emerald-500 animate-pulse" : "bg-slate-400"}`} />
              {livePoll ? "Live (10s)" : "Paused"}
            </button>
            <button
              onClick={refresh}
              className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
            >
              <RefreshCw className="w-3 h-3" /> Refresh
            </button>
            <button
              onClick={downloadCsv}
              disabled={!feed}
              className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 disabled:opacity-50"
            >
              <Download className="w-3 h-3" /> Export
            </button>
          </>
        }
      />

      {/* Right Now hero panel */}
      {feed && (
        <Card>
          <div className="grid grid-cols-1 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x divide-slate-100">
            <div className="p-5 flex items-center gap-4">
              <span className="w-12 h-12 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
                <UsersIcon className="w-5 h-5" />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Users online</p>
                <p className="text-3xl font-semibold text-emerald-600 tabular-nums leading-tight">{feed.rightNow.usersOnline}</p>
                <p className="text-[11px] text-slate-500">last 5 min</p>
              </div>
            </div>
            <div className="p-5 flex items-center gap-4">
              <span className="w-12 h-12 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
                <Globe className="w-5 h-5" />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Active brands</p>
                <p className="text-3xl font-semibold text-blue-600 tabular-nums leading-tight">{feed.rightNow.activeBrands}</p>
                <p className="text-[11px] text-slate-500">last 5 min</p>
              </div>
            </div>
            <div className="p-5 flex items-center gap-4">
              <span className="w-12 h-12 rounded-xl bg-violet-50 text-violet-600 flex items-center justify-center">
                <Clock className="w-5 h-5" />
              </span>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Events / min</p>
                <p className="text-3xl font-semibold text-violet-600 tabular-nums leading-tight">{feed.rightNow.eventsPerMinute}</p>
                <p className="text-[11px] text-slate-500">last 60s</p>
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* Filter chips */}
      <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-3 flex items-center gap-1.5 flex-wrap">
        {FILTER_CHIPS.map((c) => (
          <button
            key={c.id}
            onClick={() => { setCategoryFilter(c.id); setPage(1); }}
            className={`px-3 py-1.5 text-xs font-semibold rounded-full transition-colors ${
              categoryFilter === c.id
                ? "bg-slate-900 text-white"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200"
            }`}
          >
            {c.label}
          </button>
        ))}
      </div>

      {/* Connected timeline feed */}
      {loading && !feed ? (
        <Card>
          <div className="p-8 space-y-3">
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="flex items-center gap-3">
                <Skel className="w-2 h-2 rounded-full bg-slate-200" />
                <Skel className="w-6 h-6 rounded-full bg-slate-100" />
                <Skel className="h-3 flex-1 bg-slate-100 rounded" />
                <Skel className="w-12 h-3 bg-slate-100 rounded" />
              </div>
            ))}
          </div>
        </Card>
      ) : !feed || feed.rows.length === 0 ? (
        <Card>
          <EmptyState
            icon={Activity}
            title="No events match these filters"
            description="Telemetry populates as routes adopt trackEvent()."
          />
        </Card>
      ) : (
        <Card>
          <ul className="relative px-5 py-4 space-y-3">
            {/* Vertical rail behind every dot */}
            <span className="absolute left-[28px] top-6 bottom-6 w-px bg-slate-200" aria-hidden />
            {feed.rows.map((r) => {
              const meta = CATEGORY_META[(r.category as Category)] ?? CATEGORY_META.settings;
              const Icon = meta.icon;
              return (
                <li key={r.id} className="relative flex items-start gap-3">
                  {/* Dot on the rail */}
                  <span className={`absolute left-[24px] top-3 w-2 h-2 rounded-full ring-2 ring-white ${meta.dot}`} />
                  {/* Category icon chip */}
                  <span className={`shrink-0 w-8 h-8 rounded-lg flex items-center justify-center ${meta.chip}`}>
                    <Icon className="w-3.5 h-3.5" />
                  </span>
                  {/* Body */}
                  <button
                    onClick={() => setSelected(r)}
                    className="flex-1 text-left min-w-0 hover:bg-slate-50 -m-2 p-2 rounded-lg transition-colors"
                  >
                    <div className="flex items-center gap-2 mb-0.5">
                      {r.user ? (
                        <Avatar src={r.user.image} name={r.user.name ?? r.user.email ?? "?"} size={20} />
                      ) : (
                        <span className="w-5 h-5 rounded-full bg-slate-100 text-slate-400 text-[9px] font-bold flex items-center justify-center">SYS</span>
                      )}
                      <Link
                        href={`/admin/users?q=${encodeURIComponent(r.user?.email ?? "")}`}
                        onClick={(e) => e.stopPropagation()}
                        className="text-xs font-semibold text-slate-800 hover:text-brand-600 truncate"
                      >
                        {r.user?.name ?? r.user?.email ?? "system"}
                      </Link>
                      {r.brand && (
                        <Link
                          href={`/admin/brands?q=${encodeURIComponent(r.brand.domain ?? "")}`}
                          onClick={(e) => e.stopPropagation()}
                          className="text-[10px] text-slate-500 hover:text-brand-600 px-1.5 py-0.5 rounded bg-slate-100 truncate max-w-[160px]"
                        >
                          {r.brand.name}
                        </Link>
                      )}
                      <span className="text-[10px] text-slate-400 tabular-nums ml-auto shrink-0">{formatTime(r.timestamp)}</span>
                    </div>
                    <p className="text-xs text-slate-700 truncate">{r.action}</p>
                  </button>
                </li>
              );
            })}
          </ul>
        </Card>
      )}

      {/* Pagination */}
      {feed && feed.total > feed.limit && (
        <div className="flex items-center justify-between text-xs text-slate-500">
          <span>Page {page} of {totalPages}</span>
          <div className="flex items-center gap-2">
            <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              <ChevronLeft className="w-3 h-3" /> Prev
            </button>
            <button onClick={() => setPage((p) => p + 1)} disabled={!feed.hasMore} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              Next <ChevronRight className="w-3 h-3" />
            </button>
          </div>
        </div>
      )}

      {/* Slide-out panel — JSON metadata for debugging */}
      {selected && (
        <div className="fixed inset-0 z-40 flex animate-in fade-in duration-150" onClick={() => setSelected(null)}>
          <div className="flex-1 bg-slate-900/40" />
          <aside className="w-[420px] max-w-full bg-white border-l border-slate-200 overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <header className="px-5 py-4 border-b border-slate-200 flex items-center justify-between">
              <div>
                <h2 className="font-semibold text-slate-900 text-sm">{selected.action}</h2>
                <p className="text-[11px] text-slate-500 mt-0.5">{new Date(selected.timestamp).toLocaleString()}</p>
              </div>
              <button onClick={() => setSelected(null)} className="p-1.5 rounded-lg hover:bg-slate-100"><X className="w-4 h-4" /></button>
            </header>
            <div className="p-5 space-y-4 text-xs">
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Category</p>
                  <p className="font-semibold text-slate-800">{selected.category}</p>
                </div>
                <div>
                  <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">User</p>
                  <p className="font-semibold text-slate-800 truncate">{selected.user?.email ?? selected.user?.name ?? "system"}</p>
                </div>
                {selected.brand && (
                  <div className="col-span-2">
                    <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">Brand</p>
                    <p className="font-semibold text-slate-800">{selected.brand.name} <span className="text-slate-400 font-normal">({selected.brand.domain})</span></p>
                  </div>
                )}
              </div>
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1">Metadata</p>
                <pre className="text-[11px] bg-slate-50 border border-slate-200 rounded-lg p-3 whitespace-pre-wrap overflow-auto max-h-80">
                  {JSON.stringify(selected.metadata ?? {}, null, 2)}
                </pre>
              </div>
            </div>
          </aside>
        </div>
      )}
    </div>
  );
}
