"use client";

/**
 * Admin → Integrations
 * ────────────────────
 * Every BrandIntegration row across the platform. Headline cards
 * show connected / errored counts per integration type; the table
 * lists individual rows for triage with status, last-sync, and
 * any syncError surfaced inline.
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import { Zap, Loader2, AlertTriangle, CheckCircle2, Clock } from "lucide-react";

interface Row {
  id: string;
  integrationId: string;
  connected: boolean;
  status: string;
  lastSynced: string | null;
  syncError: string | null;
  syncRetryCount: number;
  tokenExpiresAt: string | null;
  // Present only for synthetic site_tag rows — the "installed
  // since" timestamp (first TrackedEvent). Not rendered in the
  // main table but kept on the payload so future UI tweaks can
  // surface it without another round-trip.
  installedAt?: string | null;
  brand: { id: string; name: string; domain: string };
}

// Type-badge colour per integration id. site_tag gets its own teal
// palette so it stands apart from the OAuth integrations without
// breaking the uppercase/rounded visual convention.
function typeBadgeClass(integrationId: string): string {
  if (integrationId === "site_tag") return "bg-teal-50 text-teal-700 border border-teal-200";
  return "bg-slate-100 text-slate-700";
}
function typeBadgeLabel(integrationId: string): string {
  // "site_tag" → "SITE TAG"; every other known id is already the
  // uppercase convention (gsc / ga4 / gbp / hubspot).
  return integrationId.replace(/_/g, " ").toUpperCase();
}
interface Payload {
  summary: {
    total: number;
    connected: number;
    withError: number;
    byType: Record<string, { total: number; connected: number; withError: number }>;
  };
  rows: Row[];
}

function formatDate(s: string | null): string {
  if (!s) return "—";
  try {
    const d = new Date(s);
    const ageMin = (Date.now() - d.getTime()) / 60_000;
    if (ageMin < 60) return `${Math.floor(ageMin)}m ago`;
    if (ageMin < 60 * 24) return `${Math.floor(ageMin / 60)}h ago`;
    return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  } catch { return s; }
}

export default function AdminIntegrationsPage() {
  const [data, setData] = useState<Payload | null>(null);
  const [filter, setFilter] = useState<"all" | "connected" | "error">("all");

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

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

  const filteredRows = data.rows.filter((r) =>
    filter === "all" ? true
    : filter === "connected" ? r.connected
    : !!r.syncError,
  );

  return (
    <div className="space-y-5">
      <div>
        <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
          <Zap className="w-5 h-5 text-slate-700" /> Integrations
        </h1>
        <p className="text-slate-500 text-sm mt-1">
          {data.summary.total.toLocaleString()} integration row{data.summary.total === 1 ? "" : "s"} across all brands.
        </p>
      </div>

      {/* Headline cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Stat label="Total" value={data.summary.total} color="text-slate-800" />
        <Stat label="Connected" value={data.summary.connected} color="text-emerald-600" />
        <Stat label="With errors" value={data.summary.withError} color={data.summary.withError > 0 ? "text-red-600" : "text-slate-800"} />
        <Stat label="Types" value={Object.keys(data.summary.byType).length} color="text-slate-800" />
      </div>

      {/* Per-type breakdown */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-slate-100 font-bold text-slate-800 text-sm">By integration type</div>
        <div className="divide-y divide-slate-100">
          {Object.entries(data.summary.byType).map(([id, s]) => (
            <div key={id} className="px-4 py-2.5 flex items-center gap-3">
              <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded min-w-[70px] text-center ${typeBadgeClass(id)}`}>
                {typeBadgeLabel(id)}
              </span>
              <div className="flex-1 grid grid-cols-3 gap-2 text-xs">
                <span className="text-slate-700">{s.total} total</span>
                <span className="text-emerald-600">{s.connected} connected</span>
                <span className={s.withError > 0 ? "text-red-600 font-semibold" : "text-slate-400"}>
                  {s.withError} errored
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white border border-slate-200 rounded-xl p-3 flex items-center gap-2">
        <select
          value={filter}
          onChange={(e) => setFilter(e.target.value as typeof filter)}
          className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg"
        >
          <option value="all">All ({data.summary.total})</option>
          <option value="connected">Connected ({data.summary.connected})</option>
          <option value="error">Errored ({data.summary.withError})</option>
        </select>
        <span className="text-xs text-slate-500 ml-auto">{filteredRows.length} shown</span>
      </div>

      {/* Table */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 border-b border-slate-200">
            <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
              <th className="text-left px-4 py-3">Brand</th>
              <th className="text-left px-3 py-3">Type</th>
              <th className="text-left px-3 py-3">Status</th>
              <th className="text-right px-3 py-3">Last sync</th>
              <th className="text-right px-3 py-3">Token expires</th>
              <th className="text-left px-3 py-3">Error</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {filteredRows.map((r) => (
              <tr key={r.id} className={`hover:bg-slate-50 ${r.syncError ? "bg-red-50/30" : ""}`}>
                <td className="px-4 py-2.5">
                  <Link href={`/admin/brands?q=${encodeURIComponent(r.brand.domain)}`} className="text-xs font-semibold text-slate-800 hover:text-brand-600 truncate block max-w-[200px]">
                    {r.brand.name}
                  </Link>
                  <p className="text-[10px] text-slate-500 font-mono truncate max-w-[200px]">{r.brand.domain}</p>
                </td>
                <td className="px-3 py-2.5">
                  <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${typeBadgeClass(r.integrationId)}`}>
                    {typeBadgeLabel(r.integrationId)}
                  </span>
                </td>
                <td className="px-3 py-2.5">
                  {r.connected ? (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-emerald-700">
                      <CheckCircle2 className="w-3 h-3" /> {r.status}
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-slate-500">
                      {r.status}
                    </span>
                  )}
                </td>
                <td className="px-3 py-2.5 text-right text-[10px] text-slate-500 tabular-nums">
                  {formatDate(r.lastSynced)}
                </td>
                <td className="px-3 py-2.5 text-right text-[10px] text-slate-500 tabular-nums">
                  {r.tokenExpiresAt ? (
                    <span className={new Date(r.tokenExpiresAt) < new Date() ? "text-red-600 font-semibold inline-flex items-center gap-1" : ""}>
                      {new Date(r.tokenExpiresAt) < new Date() && <Clock className="w-3 h-3" />}
                      {formatDate(r.tokenExpiresAt)}
                    </span>
                  ) : "—"}
                </td>
                <td className="px-3 py-2.5">
                  {r.syncError ? (
                    <span className="text-[10px] text-red-700 font-mono inline-flex items-center gap-1 max-w-[280px]" title={r.syncError}>
                      <AlertTriangle className="w-3 h-3 shrink-0" />
                      <span className="truncate">{r.syncError}</span>
                      {r.syncRetryCount > 0 && <span className="text-[9px] text-red-500 shrink-0">×{r.syncRetryCount}</span>}
                    </span>
                  ) : (
                    <span className="text-[10px] text-slate-400">—</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Stat({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div className="bg-white border border-slate-200 rounded-xl p-4">
      <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{label}</p>
      <p className={`text-2xl font-bold mt-1 tabular-nums ${color}`}>{value.toLocaleString()}</p>
    </div>
  );
}
