import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import { createWalletManagementApi, createApiApi } from "~/utils/api-client-factory";

export function useServiceGetWallet() {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getWalletService"],
    queryFn: async () => {
      const walletApi = createWalletManagementApi(token);
      return await walletApi.apiWalletV1WalletList();
    },
  });

  return { ...response };
}

export function useServiceCreatePayoutRequest() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: {
      amount: string;
      transaction_type: "deposit" | "purchase";
    }) => {
      const walletApi = createWalletManagementApi(token);
      const response = await walletApi.apiWalletV1ChargeCreate({
        data: {
          amount: data.amount,
          transactionType: data.transaction_type,
        },
      });
      return response;
    },
    onSuccess: (data) => {
      console.log("Charge request response:", data);
      queryClient.invalidateQueries({ queryKey: ["getWalletService"] });
    },
  });
}

// Get seller balance
export function useServiceGetSellerBalance() {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getSellerBalanceService"],
    queryFn: async () => {
      const walletApi = createWalletManagementApi(token);
      return await walletApi.apiWalletV1SellerBalanceRead();
    },
  });

  return { ...response };
}

// Get payout requests list
export function useServiceGetPayoutRequests(filters?: {
  dateFilter?: "today" | "last_7" | "last_30" | "custom";
  fromDate?: string;
  toDate?: string;
}) {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getPayoutRequestsService", filters],
    queryFn: async () => {
      const walletApi = createWalletManagementApi(token);
      return await walletApi.apiWalletV1PayoutRequestList({
        dateFilter: filters?.dateFilter,
        fromDate: filters?.fromDate,
        toDate: filters?.toDate,
      });
    },
  });

  return { ...response };
}

// Get bank accounts list
export function useServiceGetBankAccounts() {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getBankAccountsService"],
    queryFn: async () => {
      const walletApi = createWalletManagementApi(token);
      return await walletApi.apiWalletV1BankAccountsListList();
    },
  });

  return { ...response };
}

// Get financial report
export function useServiceGetReport(filters?: {
  fromDate?: string;
  toDate?: string;
}) {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getReportService", filters],
    queryFn: async () => {
      const apiApi = createApiApi(token);
      return await apiApi.apiWalletV1ReportList({
        fromDate: filters?.fromDate,
        toDate: filters?.toDate,
      });
    },
  });

  return { ...response };
}

// Create payout request (Cash money)
export function useServiceCreateCashRequest() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: { amount: string; bank_account: string }) => {
      const walletApi = createWalletManagementApi(token);
      const response = await walletApi.apiWalletV1PayoutRequestCreateCreate({
        data: {
          amount: data.amount,
          bankAccount: data.bank_account,
        },
      });
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getPayoutRequestsService"] });
      queryClient.invalidateQueries({ queryKey: ["getSellerBalanceService"] });
    },
  });
}

// Register bank account
export function useServiceRegisterBankAccount() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: { iban: string; cardNumber: string }) => {
      const walletApi = createWalletManagementApi(token);
      const response = await walletApi.apiWalletV1BankAccountsCreate({
        data: {
          iban: data.iban,
          cardNumber: data.cardNumber,
        },
      });
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getBankAccountsService"] });
    },
  });
}

// Delete bank account
export function useServiceDeleteBankAccount() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (bankAccountId: string) => {
      const walletApi = createWalletManagementApi(token);
      const response = await walletApi.apiWalletV1BankAccountsDelete({
        id: bankAccountId,
      });
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getBankAccountsService"] });
    },
  });
}

// Verify Zarinpal payment
export function useServiceVerifyPayment() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: {
      authority: string;
      status: string;
      authority_id: string;
    }) => {
      const walletApi = createWalletManagementApi(token);
      const response = await walletApi.apiWalletV1VerifyList({
        authority: data.authority,
        status: data.status,
        authorityId: data.authority_id,
      });
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getWalletService"] });
      queryClient.invalidateQueries({ queryKey: ["getSellerBalanceService"] });
    },
  });
}
