"use client";

import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { paymentApi } from "@/modules/payment/services/payment-api";
import { usePaymentHealth } from "@/modules/payment/hooks/usePaymentCapabilities";
import { PaymentPageLoader, PaymentPageError } from "@/modules/payment/pages/shared";
import { PageHeader, Card, CardContent, Badge } from "@/components/ds";
import { PaymentStatusChip } from "@/modules/payment/components/PaymentStatusChip";

export const PaymentGatewayHealth = function PaymentGatewayHealthPage() {
  const { tenantId } = useTenantId();
  const health = usePaymentHealth();

  const connectionsQ = useQuery({
    queryKey: ["payment", tenantId, "psp-health"],
    queryFn: () => paymentApi.pspConnections.list(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || connectionsQ.isLoading || health.isLoading) return <PaymentPageLoader />;
  if (connectionsQ.error) return <PaymentPageError error={connectionsQ.error} onRetry={() => connectionsQ.refetch()} />;

  return (
    <div className="space-y-6">
      <PageHeader
        title="سلامت درگاه"
        description="وضعیت سرویس و اتصالات PSP."
        actions={
          <Badge tone={health.data?.status === "ok" ? "success" : "warning"}>
            {health.data?.status ?? "—"}
          </Badge>
        }
      />
      <Card>
        <CardContent className="grid gap-2 p-4 text-sm sm:grid-cols-3">
          <p><span className="text-[var(--muted)]">سرویس:</span> {health.data?.service}</p>
          <p><span className="text-[var(--muted)]">نسخه:</span> {health.data?.version}</p>
          <p><span className="text-[var(--muted)]">وضعیت:</span> {health.data?.status}</p>
        </CardContent>
      </Card>
      <div className="grid gap-3">
        {(connectionsQ.data ?? []).map((c) => (
          <Card key={String(c.id)}>
            <CardContent className="flex flex-wrap items-center justify-between gap-2 p-4">
              <div>
                <p className="font-medium">{String(c.name ?? c.provider_code)}</p>
                <p className="text-xs text-[var(--muted)]">{String(c.provider_code)}</p>
              </div>
              <PaymentStatusChip status={String(c.status)} />
            </CardContent>
          </Card>
        ))}
        {(connectionsQ.data ?? []).length === 0 ? (
          <p className="text-sm text-[var(--muted)]">اتصال PSP ثبت نشده — از بخش مدیریت درگاه اضافه کنید.</p>
        ) : null}
      </div>
    </div>
  );
};

export default PaymentGatewayHealth;
