"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { useTenantId } from "@/hooks/useTenantId";
import { paymentApi } from "@/modules/payment/services/payment-api";
import { PaymentPageLoader, PaymentPageError, PaymentEmptyState } from "@/modules/payment/pages/shared";
import { PageHeader, Card, CardContent, Button } from "@/components/ds";
import { PaymentStatusChip } from "@/modules/payment/components/PaymentStatusChip";

export const PaymentMerchantApprovals = function PaymentMerchantApprovalsPage() {
  const { tenantId } = useTenantId();

  const q = useQuery({
    queryKey: ["payment", tenantId, "merchant-approvals"],
    queryFn: async () => {
      const all = await paymentApi.merchants.list(tenantId!);
      return all.filter((m) => m.status === "pending_review");
    },
    enabled: !!tenantId,
  });

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

  const pending = q.data ?? [];

  return (
    <div className="space-y-6">
      <PageHeader title="تأیید پذیرندگان" description="حساب‌های در انتظار بررسی (pending_review)." />
      {pending.length === 0 ? (
        <PaymentEmptyState title="درخواست تأییدی در صف نیست" />
      ) : (
        <div className="grid gap-3">
          {pending.map((m) => (
            <Card key={String(m.id)}>
              <CardContent className="flex flex-wrap items-center justify-between gap-2 p-4">
                <div>
                  <p className="font-medium">{String(m.name)}</p>
                  <p className="text-xs text-[var(--muted)]">{String(m.code)}</p>
                </div>
                <div className="flex items-center gap-2">
                  <PaymentStatusChip status={String(m.status)} />
                  <Link href={`/payment/merchants/${m.id}`}>
                    <Button size="sm" variant="outline">بررسی</Button>
                  </Link>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default PaymentMerchantApprovals;
