// @File: frontend/src/pages/admin/cms/CmsApiPayments.tsx
// @Desc: API Hub → Payments tab. Lists payment gateways: PayPal,
//        Payoneer, Stripe, and manual bank transfer.
import { useCallback, useEffect, useState } from "react";
import { CreditCard, Loader2, RefreshCw } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard } from "./ui";
import ApiHubProviderCard from "./ApiHubProviderCard";
import { fetchPayments, type ProviderStatus } from "@/lib/apiHub";

export default function CmsApiPayments() {
  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 fetchPayments();
      setItems(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load payments.");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

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

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

  return (
    <CmsLayout>
      <PageHeader
        title="API Hub · Payments"
        description="Payment gateways and payout methods available at checkout: PayPal, Payoneer, Stripe, and bank transfer."
        icon={<CreditCard 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 payment providers…">
          <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 payments.">
          <div className="text-sm text-red-600">{error}</div>
        </SectionCard>
      )}

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