"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft, Check, X, Globe, Users, Building2, BarChart3,
  Tag, Search, FileText, Bot, Plug, Loader2,
} from "lucide-react";

interface BrandStats {
  sessions30d: number;
  conversions30d: number;
  gscClicks28d: number;
  gscImpressions28d: number;
  trackedKeywords: number;
  contentBriefs: number;
  pluginsDetected: string[];
}

interface BrandDetail {
  id: string;
  name: string;
  domain: string;
  plan: string | null;
  industry: string | null;
  createdAt: string;
  integrations: Array<{ integrationId: string; connected: boolean; lastSynced: string | null }>;
  siteTag: { siteId: string; status: string; firstEventAt: string | null; lastEventAt: string | null } | null;
  stats: BrandStats | null;
}

interface OrgDetail {
  organization: {
    id: string;
    name: string;
    createdAt: string;
    brands: BrandDetail[];
    memberships: Array<{ role: string; joinedAt: string; user: { id: string; name: string | null; email: string; image: string | null } }>;
  };
  aiUsage: { calls: number; cost: number };
}

function fmt(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();
}

function relDate(iso: string | null): string {
  if (!iso) return "—";
  const sec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return "just now";
  if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
  if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
  return `${Math.floor(sec / 86400)}d ago`;
}

export default function AdminOrgDetail() {
  const { id } = useParams();
  const [data, setData] = useState<OrgDetail | null>(null);

  useEffect(() => {
    fetch(`/api/admin/organizations/${id}`)
      .then((r) => (r.ok ? r.json() : null))
      .then(setData)
      .catch(() => {});
  }, [id]);

  if (!data) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-6 h-6 text-slate-400 animate-spin" />
      </div>
    );
  }

  const org = data.organization;
  const totalSessions = org.brands.reduce((s, b) => s + (b.stats?.sessions30d ?? 0), 0);
  const totalConversions = org.brands.reduce((s, b) => s + (b.stats?.conversions30d ?? 0), 0);
  const totalClicks = org.brands.reduce((s, b) => s + (b.stats?.gscClicks28d ?? 0), 0);

  return (
    <div className="space-y-6 max-w-6xl">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Link href="/admin/organizations" className="p-1.5 rounded-lg hover:bg-white text-slate-500">
          <ArrowLeft className="w-4 h-4" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-slate-900">{org.name}</h1>
          <p className="text-xs text-slate-500">
            Created {new Date(org.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
            {" · "}{org.memberships.length} user{org.memberships.length !== 1 ? "s" : ""}
            {" · "}{org.brands.length} brand{org.brands.length !== 1 ? "s" : ""}
          </p>
        </div>
      </div>

      {/* Summary stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
        <StatBox label="Brands" value={org.brands.length} icon={Building2} />
        <StatBox label="Sessions (30d)" value={fmt(totalSessions)} icon={BarChart3} color="text-emerald-600" />
        <StatBox label="Conversions (30d)" value={fmt(totalConversions)} icon={Tag} color="text-blue-600" />
        <StatBox label="GSC Clicks (28d)" value={fmt(totalClicks)} icon={Search} color="text-violet-600" />
        <StatBox label="AI Cost (30d)" value={`$${data.aiUsage.cost}`} icon={Bot} color="text-amber-600" />
      </div>

      {/* Members */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2">
          <Users className="w-4 h-4 text-slate-500" />
          <h2 className="font-bold text-slate-800 text-sm">Members ({org.memberships.length})</h2>
        </div>
        <div className="divide-y divide-slate-100">
          {org.memberships.map((m) => (
            <div key={m.user.id} className="px-5 py-2.5 flex items-center gap-3">
              {m.user.image ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={m.user.image} alt="" className="w-7 h-7 rounded-full" />
              ) : (
                <div className="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-[11px] font-bold text-slate-600">
                  {(m.user.name || m.user.email)[0]?.toUpperCase()}
                </div>
              )}
              <div className="flex-1 min-w-0">
                <span className="text-sm font-semibold text-slate-900 mr-2">{m.user.name || "—"}</span>
                <span className="text-xs text-slate-500">{m.user.email}</span>
              </div>
              <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">{m.role}</span>
              <span className="text-[10px] text-slate-400">{relDate(m.joinedAt)}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Brands — detailed cards */}
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Building2 className="w-4 h-4 text-slate-500" />
          <h2 className="font-bold text-slate-800 text-sm">Brands ({org.brands.length})</h2>
        </div>

        {org.brands.map((brand) => (
          <BrandCard key={brand.id} brand={brand} />
        ))}
      </div>
    </div>
  );
}

function StatBox({ label, value, icon: Icon, color }: { label: string; value: string | number; icon: typeof Building2; color?: string }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
      <div className="flex items-center gap-1.5 mb-1">
        <Icon className="w-3.5 h-3.5 text-slate-400" />
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{label}</p>
      </div>
      <p className={`text-2xl font-bold ${color ?? "text-slate-900"}`}>{value}</p>
    </div>
  );
}

function BrandCard({ brand }: { brand: BrandDetail }) {
  const s = brand.stats;
  const has = (id: string) => brand.integrations.some((i) => i.integrationId === id && i.connected);

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      {/* Brand header */}
      <div className="px-5 py-4 border-b border-slate-100 flex items-start justify-between">
        <div>
          <h3 className="text-sm font-bold text-slate-900">{brand.name}</h3>
          <a href={`https://${brand.domain}`} target="_blank" rel="noreferrer" className="text-xs font-mono text-brand-600 hover:underline">
            {brand.domain}
          </a>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          {brand.plan && (
            <span className="text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-slate-100 text-slate-600 border border-slate-200">
              {brand.plan}
            </span>
          )}
          {brand.siteTag?.firstEventAt && (
            <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200">
              Site Tag Active
            </span>
          )}
        </div>
      </div>

      {/* Integrations + Site Tag info */}
      <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-3 flex-wrap">
        <IntDot on={has("gsc")} label="GSC" />
        <IntDot on={has("ga4")} label="GA4" />
        <IntDot on={has("gbp")} label="GBP" />
        <IntDot on={!!brand.siteTag} label="Site Tag" />
        {brand.siteTag && (
          <>
            <span className="text-[10px] text-slate-400 ml-auto">
              ID: <span className="font-mono">{brand.siteTag.siteId.slice(0, 12)}…</span>
            </span>
            <span className="text-[10px] text-slate-400">
              Last event: {relDate(brand.siteTag.lastEventAt)}
            </span>
          </>
        )}
      </div>

      {/* Usage stats grid */}
      {s && (
        <div className="px-5 py-4 grid grid-cols-3 md:grid-cols-6 gap-3">
          <MiniStat label="Sessions (30d)" value={fmt(s.sessions30d)} />
          <MiniStat label="Conversions (30d)" value={fmt(s.conversions30d)} />
          <MiniStat label="GSC Clicks (28d)" value={fmt(s.gscClicks28d)} />
          <MiniStat label="GSC Impr (28d)" value={fmt(s.gscImpressions28d)} />
          <MiniStat label="Tracked Keywords" value={s.trackedKeywords} />
          <MiniStat label="Content Briefs" value={s.contentBriefs} />
        </div>
      )}

      {/* Plugins detected */}
      {s && s.pluginsDetected.length > 0 && (
        <div className="px-5 py-3 border-t border-slate-100">
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">Plugins Detected</p>
          <div className="flex flex-wrap gap-1">
            {s.pluginsDetected.map((p) => (
              <span key={p} className="text-[10px] font-semibold px-2 py-0.5 rounded bg-blue-50 text-blue-700 border border-blue-200">
                {p}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function IntDot({ on, label }: { on: boolean; label: string }) {
  return (
    <span className="inline-flex items-center gap-1 text-[10px] font-semibold">
      <span className={`w-1.5 h-1.5 rounded-full ${on ? "bg-emerald-500" : "bg-slate-300"}`} />
      <span className={on ? "text-slate-700" : "text-slate-400"}>{label}</span>
    </span>
  );
}

function MiniStat({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="bg-slate-50 rounded-lg px-3 py-2">
      <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">{label}</p>
      <p className="text-sm font-bold text-slate-800 tabular-nums mt-0.5">{value}</p>
    </div>
  );
}
