// @File: frontend/src/pages/admin/cms/CmsApiIntegrations.tsx
// @Desc: API Hub → Integrations tab. Lists core platform integrations
//        (WHMCS billing, CRM, analytics) with full per-provider detail.
import { useCallback, useEffect, useState } from "react";
import { Activity, Loader2, RefreshCw } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard } from "./ui";
import ApiHubProviderCard from "./ApiHubProviderCard";
import { fetchIntegrations, type ProviderStatus } from "@/lib/apiHub";

export default function CmsApiIntegrations() {
  const [items, setItems] = useState<ProviderStatus[]>([]);
  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 fetchIntegrations();
      setItems(result);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to load integrations.",
      );
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

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

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

  return (
    <CmsLayout>
      <PageHeader
        title="API Hub · Integrations"
        description="Core platform integrations such as WHMCS billing, CRM, and analytics tracking."
        icon={<Activity 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 && items.length === 0 && (
        <SectionCard title="Loading" description="Fetching integrations…">
          <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 integrations."
        >
          <div className="text-sm text-red-600">{error}</div>
        </SectionCard>
      )}

      {!loading && items.length === 0 && !error && (
        <SectionCard
          title="No integrations"
          description="No integration providers are currently registered."
        >
          <div className="text-sm text-slate-500 py-4">
            Add providers in the backend registry to see them here.
          </div>
        </SectionCard>
      )}

      <div className="space-y-5">
        {items.map((provider) => (
          <ApiHubProviderCard
            key={provider.id}
            provider={provider}
            onTested={handleRefresh}
          />
        ))}
      </div>
    </CmsLayout>
  );
}