// @File: frontend/src/pages/admin/cms/CmsApiHub.tsx
// @Desc: Admin → API Hub landing dashboard. Lists every outbound API the
//        portal integrates with, grouped into three categories
//        (integrations / notifications / payments). Each card shows:
//          - name + short description
//          - live status badge (connected / configured / error / not configured)
//          - last tested-at timestamp + latency
//          - "Test" button that hits the backend probe for that provider
//          - link to the dedicated category page for deeper details
//        Data source: GET /api/v1/admin/api-hub/status
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import {
  Plug,
  RefreshCw,
  Loader2,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  CircleDashed,
  ExternalLink,
  ArrowRight,
  Activity,
  Bell,
  CreditCard,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Badge } from "./ui";
import {
  fetchApiHubStatus,
  testProvider,
  statusTone,
  statusLabel,
  formatRelativeTimestamp,
  type ApiHubAggregate,
  type ProviderStatus,
  type ProviderStatusValue,
} from "@/lib/apiHub";

function StatusIcon({ status }: { status: ProviderStatusValue }) {
  switch (status) {
    case "connected":
      return <CheckCircle2 className="w-4 h-4 text-emerald-600" />;
    case "configured":
      return <AlertTriangle className="w-4 h-4 text-amber-500" />;
    case "error":
      return <XCircle className="w-4 h-4 text-red-600" />;
    default:
      return <CircleDashed className="w-4 h-4 text-slate-400" />;
  }
}

function ProviderCard({
  provider,
  onTested,
}: {
  provider: ProviderStatus;
  onTested: () => void;
}) {
  const [testing, setTesting] = useState(false);
  const tone = statusTone(provider.status);
  const requiredMissing = provider.credentials
    .filter((c) => c.required && !c.present)
    .map((c) => c.name);

  const handleTest = useCallback(async () => {
    if (!provider.test_supported) return;
    setTesting(true);
    try {
      const result = await testProvider(provider.id);
      if (result.ok) {
        toast.success(`${provider.name}: ${result.message}`);
      } else {
        const ipHint = result.outbound_ip
          ? ` (outbound IP: ${result.outbound_ip})`
          : "";
        toast.error(`${provider.name}: ${result.message}${ipHint}`);
      }
      onTested();
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Failed to run provider test.",
      );
    } finally {
      setTesting(false);
    }
  }, [provider.id, provider.name, provider.test_supported, onTested]);

  return (
    <div className="border border-slate-200 rounded-xl p-4 bg-white hover:shadow-md transition flex flex-col gap-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <StatusIcon status={provider.status} />
            <h4 className="font-bold text-slate-900 truncate">{provider.name}</h4>
            {provider.sandbox_mode && (
              <Badge tone="blue">Sandbox</Badge>
            )}
          </div>
          <p className="text-xs text-slate-500 mt-1 line-clamp-2">
            {provider.description}
          </p>
        </div>
        <Badge tone={tone}>{statusLabel(provider.status)}</Badge>
      </div>

      <div className="text-[11px] text-slate-500 space-y-1">
        <div className="flex items-center justify-between">
          <span>Last test</span>
          <span className="font-mono">
            {formatRelativeTimestamp(provider.last_checked_at)}
          </span>
        </div>
        {provider.latency_ms !== null && (
          <div className="flex items-center justify-between">
            <span>Latency</span>
            <span className="font-mono">{provider.latency_ms} ms</span>
          </div>
        )}
        {requiredMissing.length > 0 && (
          <div className="text-red-600">
            Missing: {requiredMissing.join(", ")}
          </div>
        )}
      </div>

      <div className="flex items-center gap-2 pt-2 mt-auto border-t border-slate-100">
        <button
          type="button"
          onClick={handleTest}
          disabled={testing || !provider.test_supported}
          className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition disabled:opacity-50 disabled:cursor-not-allowed"
          title={
            provider.test_supported
              ? "Run a live connectivity test"
              : "Live testing not supported for this provider"
          }
        >
          {testing ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
          ) : (
            <RefreshCw className="w-3.5 h-3.5" />
          )}
          {testing ? "Testing…" : "Test"}
        </button>
        {provider.docs_url && (
          <a
            href={provider.docs_url}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 px-3 py-2 rounded-lg border border-slate-300 text-slate-700 text-xs font-semibold hover:bg-slate-50 transition"
          >
            Docs
            <ExternalLink className="w-3 h-3" />
          </a>
        )}
      </div>
    </div>
  );
}

function CategorySection({
  title,
  icon,
  description,
  providers,
  seeAllHref,
  onTested,
}: {
  title: string;
  icon: React.ReactNode;
  description: string;
  providers: ProviderStatus[];
  seeAllHref: string;
  onTested: () => void;
}) {
  return (
    <SectionCard
      title={title}
      description={description}
      actions={
        <Link
          to={seeAllHref}
          className="inline-flex items-center gap-1 text-sm font-semibold text-[#0b6e3e] hover:underline"
        >
          Manage
          <ArrowRight className="w-4 h-4" />
        </Link>
      }
    >
      <div className="flex items-center gap-2 text-slate-500 text-xs -mt-1 mb-2">
        {icon}
        <span>{providers.length} providers</span>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
        {providers.map((p) => (
          <ProviderCard key={p.id} provider={p} onTested={onTested} />
        ))}
      </div>
    </SectionCard>
  );
}

export default function CmsApiHub() {
  const [data, setData] = useState<ApiHubAggregate | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      setError(null);
      const result = await fetchApiHubStatus();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load API Hub.");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

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

  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    void load();
  }, [load]);

  const summaryStats = useMemo(() => {
    if (!data) return null;
    return [
      { label: "Total", value: data.summary.total, tone: "slate" as const },
      {
        label: "Connected",
        value: data.summary.connected,
        tone: "green" as const,
      },
      {
        label: "Configured",
        value: data.summary.configured,
        tone: "yellow" as const,
      },
      { label: "Error", value: data.summary.error, tone: "red" as const },
      {
        label: "Not configured",
        value: data.summary.not_configured,
        tone: "slate" as const,
      },
    ];
  }, [data]);

  return (
    <CmsLayout>
      <PageHeader
        title="API Hub"
        description="Unified view of every outbound API integration the portal uses. Test connectivity, inspect credentials, and jump into each category."
        icon={<Plug className="w-6 h-6" />}
      />

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

      {loading && !data && (
        <SectionCard title="Loading" description="Fetching API Hub status…">
          <div className="flex items-center justify-center py-10 text-slate-500">
            <Loader2 className="w-6 h-6 animate-spin" />
          </div>
        </SectionCard>
      )}

      {error && (
        <SectionCard title="Error" description="Failed to load API Hub status.">
          <div className="text-sm text-red-600">{error}</div>
        </SectionCard>
      )}

      {data && summaryStats && (
        <>
          <SectionCard
            title="Overview"
            description="Aggregate health of every configured provider."
          >
            <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
              {summaryStats.map((s) => (
                <div
                  key={s.label}
                  className="p-4 rounded-xl border border-slate-200 bg-white"
                >
                  <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                    {s.label}
                  </div>
                  <div className="mt-1 flex items-center gap-2">
                    <div className="text-2xl font-extrabold text-slate-900">
                      {s.value}
                    </div>
                    <Badge tone={s.tone}>{s.label}</Badge>
                  </div>
                </div>
              ))}
            </div>
          </SectionCard>

          <div className="space-y-6 mt-6">
            <CategorySection
              title="Integrations"
              icon={<Activity className="w-4 h-4" />}
              description="Core platform integrations that power the portal (billing, CRM, analytics)."
              providers={data.integrations}
              seeAllHref="/admin/cms/api-hub/integrations"
              onTested={handleRefresh}
            />
            <CategorySection
              title="Notifications"
              icon={<Bell className="w-4 h-4" />}
              description="SMS, WhatsApp, email, and push providers used to reach customers."
              providers={data.notifications}
              seeAllHref="/admin/cms/api-hub/notifications"
              onTested={handleRefresh}
            />
            <CategorySection
              title="Payments"
              icon={<CreditCard className="w-4 h-4" />}
              description="Payment gateways and manual payout methods available at checkout."
              providers={data.payments}
              seeAllHref="/admin/cms/api-hub/payments"
              onTested={handleRefresh}
            />
          </div>
        </>
      )}
    </CmsLayout>
  );
}