"use client";

import { useParams } from "next/navigation";
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 } from "@/modules/payment/pages/shared";
import { PageHeader, Card, CardContent, Button } from "@/components/ds";
import { PaymentStatusChip } from "@/modules/payment/components/PaymentStatusChip";

export const PaymentTransactionDetail = function PaymentTransactionDetailPage() {
  const params = useParams();
  const id = String(params?.id ?? "");
  const { tenantId } = useTenantId();

  const q = useQuery({
    queryKey: ["payment", tenantId, "transaction", id],
    queryFn: () => paymentApi.transactions.get(tenantId!, id),
    enabled: !!tenantId && !!id,
  });

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

  const tx = q.data!;

  return (
    <div className="space-y-6">
      <PageHeader
        title="جزئیات تراکنش"
        description={`شناسه: ${id}`}
        actions={
          tx.payment_request_id ? (
            <Link href={`/payment/requests/${tx.payment_request_id}`}>
              <Button variant="outline" size="sm">درخواست مرتبط</Button>
            </Link>
          ) : null
        }
      />
      <Card>
        <CardContent className="space-y-3 p-4 text-sm">
          <div className="flex items-center gap-2">
            <span className="text-[var(--muted)]">وضعیت:</span>
            <PaymentStatusChip status={String(tx.status)} />
          </div>
          <p><span className="text-[var(--muted)]">مبلغ:</span> {String(tx.amount_minor)} {String(tx.currency)}</p>
          <p><span className="text-[var(--muted)]">شناسه PSP:</span> {String(tx.provider_transaction_id ?? "—")}</p>
          <p><span className="text-[var(--muted)]">تاریخ:</span>{" "}
            {tx.created_at ? new Date(String(tx.created_at)).toLocaleString("fa-IR") : "—"}
          </p>
        </CardContent>
      </Card>
      <Card>
        <CardContent className="p-4">
          <h3 className="mb-2 text-sm font-semibold">داده کامل</h3>
          <pre className="overflow-x-auto text-xs">{JSON.stringify(tx, null, 2)}</pre>
        </CardContent>
      </Card>
    </div>
  );
};

export default PaymentTransactionDetail;
