"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ds";
import { PaymentListPage } from "@/modules/payment/components/PaymentListPage";
import { paymentApi } from "@/modules/payment/services/payment-api";
import { useTenantId } from "@/hooks/useTenantId";
import type { PaymentRecord } from "@/modules/payment/types";

function TestConnectionButton({ row, refresh }: { row: PaymentRecord; refresh: () => void }) {
  const { tenantId } = useTenantId();
  const qc = useQueryClient();
  const testM = useMutation({
    mutationFn: () => paymentApi.pspConnections.test(tenantId!, String(row.id)),
    onSuccess: () => {
      toast.success("تست اتصال موفق");
      refresh();
      qc.invalidateQueries({ queryKey: ["payment", tenantId] });
    },
    onError: (e: Error) => toast.error(e.message),
  });
  return (
    <Button size="sm" variant="outline" loading={testM.isPending} onClick={() => testM.mutate()}>
      تست
    </Button>
  );
}

export const PaymentPsp = function PaymentPspPage() {
  return (
    <PaymentListPage
      title="مدیریت درگاه PSP"
      description="اتصالات BYO-PSP — نیازمند باندل payment.byo_psp.basic"
      resourceKey="psp-connections"
      fetcher={(tenantId) => paymentApi.pspConnections.list(tenantId)}
      columns={[
        { key: "provider_code", header: "ارائه‌دهنده" },
        { key: "name", header: "نام" },
        { key: "status", header: "وضعیت", type: "status" },
        { key: "created_at", header: "تاریخ", type: "datetime" },
      ]}
      rowActions={(row, refresh) => <TestConnectionButton row={row} refresh={refresh} />}
    />
  );
};

export default PaymentPsp;
