"use client";

import { useState, useEffect } from "react";
import {
  DollarSign, TrendingUp, MousePointerClick, Eye, Users, Home,
  GitBranch, Zap, Plug, Globe, BarChart3,
} from "lucide-react";

interface Summary {
  totalSpend: number;
  totalClicks: number;
  totalImpressions: number;
  platformConversions: number;
  attributionPaths: number;
  adClickEvents: number;
  visitorProfiles: number;
  householdClusters: number;
  connectedPlatforms: number;
}

interface BrandRow {
  brandId: string;
  name: string;
  domain: string;
  attributionPaths: number;
  integrations: Array<{ platform: string; status: string }>;
}

interface Data {
  summary: Summary;
  topBrands: BrandRow[];
}

export default function AdminPaidMediaPage() {
  const [data, setData] = useState<Data | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/paid-media")
      .then((r) => r.ok ? r.json() : null)
      .then((d: Data | null) => setData(d))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-24">
        <div className="w-6 h-6 border-2 border-brand-600 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (!data) {
    return (
      <div className="max-w-5xl mx-auto px-6 py-12 text-center">
        <Zap className="w-10 h-10 text-slate-200 mx-auto mb-3" />
        <h2 className="text-lg font-bold text-slate-900">Paid Media Intelligence</h2>
        <p className="text-sm text-slate-500 mt-1">No data available. Run the paid-media rebuild cron first.</p>
      </div>
    );
  }

  const s = data.summary;
  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Paid Media — Platform Overview</h1>
        <p className="text-sm text-slate-500 mt-1">Cross-brand paid media attribution, spend, and platform integrations (28d)</p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-4">
        <KPI icon={DollarSign} label="Total Spend" value={`$${Math.round(s.totalSpend).toLocaleString()}`} accent="text-amber-600" />
        <KPI icon={MousePointerClick} label="Ad Clicks" value={s.totalClicks.toLocaleString()} />
        <KPI icon={Eye} label="Impressions" value={fmtLarge(s.totalImpressions)} />
        <KPI icon={TrendingUp} label="Platform Conv." value={s.platformConversions.toLocaleString()} accent="text-amber-600" />
        <KPI icon={GitBranch} label="Attribution Paths" value={s.attributionPaths.toLocaleString()} accent="text-emerald-600" />
        <KPI icon={Zap} label="Ad Click Events" value={s.adClickEvents.toLocaleString()} />
        <KPI icon={Users} label="Visitor Profiles" value={s.visitorProfiles.toLocaleString()} accent="text-violet-600" />
        <KPI icon={Home} label="Household Clusters" value={s.householdClusters.toLocaleString()} accent="text-violet-600" />
        <KPI icon={Plug} label="Connected Platforms" value={String(s.connectedPlatforms)} accent="text-emerald-600" />
      </div>

      {data.topBrands.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <BarChart3 className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Top Brands by Attribution Paths</h3>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
                <th className="px-5 py-2">Brand</th>
                <th className="px-5 py-2">Domain</th>
                <th className="px-5 py-2 text-right">Paths</th>
                <th className="px-5 py-2">Platforms</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data.topBrands.map((b) => (
                <tr key={b.brandId} className="hover:bg-slate-50">
                  <td className="px-5 py-2.5 font-medium text-slate-800">{b.name}</td>
                  <td className="px-5 py-2.5 text-slate-500 text-xs">{b.domain}</td>
                  <td className="px-5 py-2.5 text-right tabular-nums font-semibold text-slate-900">{b.attributionPaths}</td>
                  <td className="px-5 py-2.5">
                    <div className="flex gap-1 flex-wrap">
                      {b.integrations.length > 0 ? b.integrations.map((integ) => (
                        <span key={integ.platform} className={`text-[10px] px-1.5 py-0.5 rounded ${
                          integ.status === "connected" ? "bg-emerald-50 text-emerald-700" : "bg-slate-100 text-slate-500"
                        }`}>
                          {integ.platform.replace(/_/g, " ")}
                        </span>
                      )) : (
                        <span className="text-[10px] text-slate-400">Site Tag only</span>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function KPI({ icon: Icon, label, value, accent = "text-brand-600" }: {
  icon: typeof DollarSign; label: string; value: string; accent?: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-4 py-3">
      <div className="flex items-center gap-1.5 mb-1">
        <Icon className={`w-3.5 h-3.5 ${accent}`} />
        <span className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">{label}</span>
      </div>
      <p className="text-xl font-bold text-slate-900 tabular-nums">{value}</p>
    </div>
  );
}

function fmtLarge(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return n.toLocaleString();
}
