// @File: src/pages/admin/cms/CmsVisitorOverview.tsx
// @Desc: Visitor Monitor overview dashboard with 6 KPI cards + quick links
//        to the other Visitor Monitor sub-pages.
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Activity,
  ArrowUpRight,
  BarChart3,
  Link as LinkIcon,
  Loader2,
  Megaphone,
  MousePointerClick,
  RefreshCw,
  Route,
  ShieldCheck,
  Users,
} from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard } from "./ui";
import { vmGetOverview, type VmOverview } from "@/lib/adminApi";

interface KpiProps {
  label: string;
  value: string;
  icon: React.ComponentType<{ className?: string }>;
  accent: string;
  hint?: string;
}

function KpiCard({ label, value, icon: Icon, accent, hint }: KpiProps) {
  return (
    <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 hover:shadow-md transition">
      <div className="flex items-start justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-wider text-slate-500">
            {label}
          </div>
          <div className="text-3xl font-extrabold text-slate-900 mt-2">{value}</div>
          {hint && <div className="text-xs text-slate-400 mt-1">{hint}</div>}
        </div>
        <div className={`w-11 h-11 rounded-xl flex items-center justify-center ${accent}`}>
          <Icon className="w-5 h-5" />
        </div>
      </div>
    </div>
  );
}

const QUICK_LINKS = [
  {
    to: "/admin/cms/visitor-monitor/live",
    label: "Live Visitors",
    desc: "Who is on the site right now",
    icon: Activity,
  },
  {
    to: "/admin/cms/visitor-monitor/campaigns",
    label: "Campaigns",
    desc: "Generate and manage UTM links",
    icon: Megaphone,
  },
  {
    to: "/admin/cms/visitor-monitor/reports",
    label: "Reports",
    desc: "Traffic, source, device & geo",
    icon: BarChart3,
  },
  {
    to: "/admin/cms/visitor-monitor/journey",
    label: "Visitor Journey",
    desc: "Per-session timeline",
    icon: Route,
  },
  {
    to: "/admin/cms/visitor-monitor/settings",
    label: "Privacy & Settings",
    desc: "Retention, IP exclusions, masking",
    icon: ShieldCheck,
  },
];

export default function CmsVisitorOverview() {
  const [data, setData] = useState<VmOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const d = await vmGetOverview();
      setData(d);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load overview");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const fmt = (n: number | undefined) => (n ?? 0).toLocaleString();
  const pct = (n: number | undefined) => `${(n ?? 0).toFixed(1)}%`;

  return (
    <CmsLayout>
      <PageHeader
        title="Visitor Monitor"
        description="Live traffic, campaign clicks, conversions and visitor journeys."
        icon={<Activity className="w-6 h-6" />}
      />

      <div className="mb-6 flex justify-end">
        <button
          onClick={() => void load()}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-slate-300 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-50 transition"
        >
          {loading ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <RefreshCw className="w-4 h-4" />
          )}
          Refresh
        </button>
      </div>

      {error && (
        <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-200 text-sm text-red-700">
          {error}
        </div>
      )}

      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
        <KpiCard
          label="Total Visits"
          value={fmt(data?.total_visits)}
          icon={MousePointerClick}
          accent="bg-sky-50 text-sky-600"
        />
        <KpiCard
          label="Unique Visitors"
          value={fmt(data?.unique_visitors)}
          icon={Users}
          accent="bg-emerald-50 text-emerald-600"
        />
        <KpiCard
          label="Campaign Clicks"
          value={fmt(data?.campaign_clicks)}
          icon={Megaphone}
          accent="bg-violet-50 text-violet-600"
        />
        <KpiCard
          label="Referral Clicks"
          value={fmt(data?.referral_clicks)}
          icon={LinkIcon}
          accent="bg-indigo-50 text-indigo-600"
        />
        <KpiCard
          label="Conversion Rate"
          value={pct(data?.conversion_rate)}
          icon={BarChart3}
          accent="bg-amber-50 text-amber-600"
          hint="Sessions that became lead, signup, or order"
        />
        <KpiCard
          label="Active Now"
          value={fmt(data?.active_now)}
          icon={Activity}
          accent="bg-green-50 text-green-600"
          hint="Last 2 minutes"
        />
      </div>

      <SectionCard
        title="Modules"
        description="Dive into live visitors, campaigns, reports, journeys and settings."
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {QUICK_LINKS.map(({ to, label, desc, icon: Icon }) => (
            <Link
              key={to}
              to={to}
              className="group flex items-center gap-4 p-4 rounded-xl border border-slate-200 hover:border-[#0b6e3e] hover:bg-emerald-50/40 transition"
            >
              <div className="w-10 h-10 rounded-lg bg-slate-100 text-slate-700 flex items-center justify-center group-hover:bg-[#0b6e3e] group-hover:text-white transition">
                <Icon className="w-5 h-5" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-bold text-slate-900">{label}</div>
                <div className="text-xs text-slate-500 truncate">{desc}</div>
              </div>
              <ArrowUpRight className="w-4 h-4 text-slate-400 group-hover:text-[#0b6e3e]" />
            </Link>
          ))}
        </div>
      </SectionCard>
    </CmsLayout>
  );
}