import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { AdminUser } from "./useUsersFetch";
import { apiGet } from "../../../../lib/api/methods";
import { ADMIN_USERS } from "./endpoints";

type ApiKey = {
  apiKey: string;
};

export type UserViewCreditHistory = {
  uuid: string;
  credits: string;
  referenceType: string;
  createdAt: string;
};

type Wallet = {
  balance: number;
  transactions: UserViewCreditHistory[];
};

export type PaymentTransaction = {
  packageName: string;
  credits: number;
  createdAt: string;
  amount: string;
  status: string;
};

type UserDetail = Pick<
  AdminUser,
  | "uuid"
  | "createdAt"
  | "firstName"
  | "lastName"
  | "email"
  | "isActive"
  | "profilePicture"
>;

type UserDetailResponse = UserDetail & {
  apiKeys: ApiKey[];
  wallet: Wallet;
  paymentTransactions: PaymentTransaction[];
  totalCreditSpent: number;
  latestPackage?: any;
};

export default function useUserDetail() {
  const { id } = useParams<{ id: string }>();
  const { data, isPending, isError, error } = useQuery({
    queryKey: ["user-detail", id],
    queryFn: async () => {
      const res = await apiGet<UserDetailResponse>(ADMIN_USERS.USER_DETAIL(id));
      return res.data;
    },
    staleTime: 2 * 60 * 1000,
    retry: false,
    enabled: !!id,
  });

  return { user: data, loading: isPending, error, isError };
}
