import { useMutation, useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";

import { PAYMENTS_TYPE } from "../constants/app";
import { QueryKeys } from "../constants/query-keys";
import { UsersService } from "../services/api";
import {
  proceedGetPaymentMethodAssetsAsync,
  proceedGetPaymentMethodsAsync,
} from "../services/payment-method.service";
import { PaymentType } from "../types/payments";
import { withTimeout } from "../utils/app.util";

export function usePayments({ type }: { type?: PaymentType }) {
  const [assets, setAssets] = useState<any[]>();
  const [isMigrationPaymentsAPILoading, setIsMigrationPaymentsAPILoading] =
    useState<boolean>(true);

  const [migrationPayments, setMigrationPayments] = useState<any[]>();

  const paymentData = useMemo(
    () => ({
      shipping: type === PAYMENTS_TYPE.SHIPPING ? true : undefined,
    }),
    [type],
  );

  const {
    data: payments,
    // refetch: getPayments,
    isLoading: paymentsMethodLoading,
  } = useQuery({
    queryKey: [QueryKeys.payments.GET_PAYMENTS, type],
    queryFn: () => proceedGetPaymentMethodsAsync(paymentData),
    enabled: !!type,
  });

  const {
    mutate: getMigrationPaymentsAPI,
    // isPending: isMigrationPaymentsAPILoading,
  } = useMutation({
    mutationKey: [QueryKeys.payments.GET_MIGRATION_PAYMENTS],
    retry: 5,
    retryDelay: 1000,
    mutationFn: async () => {
      console.log("calling proceedGetPaymentMethodsAsync...");
      setIsMigrationPaymentsAPILoading(true);

      return await withTimeout(
        proceedGetPaymentMethodsAsync({ shipping: false }),

        3000, // 3 seconds timeout
      );
    },
    onSuccess: (data) => {
      setIsMigrationPaymentsAPILoading(false);
      console.log("🚀 ~ usePayments ~ data:", data);
      if (data) setMigrationPayments(data);
    },
    onError: (error) => {
      setIsMigrationPaymentsAPILoading(false);
      console.log("🚀 ~ usePayments ~ error:", error);
    },
  });

  const { mutate: getAssetsAPI, isPending: isLoadingAsset } = useMutation({
    mutationKey: [QueryKeys.payments.GET_ASSETS],
    mutationFn: ({ methodId }: { methodId: number }) => {
      return proceedGetPaymentMethodAssetsAsync({
        methodId,
      });
    },
    onSuccess: (data) => {
      if (data) setAssets(data);
    },
    onError: (error) => {
      console.log("🚀 ~ usePayments ~ error:", error);
    },
  });

  const acceptWalletConsent = useMutation({
    mutationKey: [QueryKeys.payments.ACCEPT_WALLET_CONSENT],
    mutationFn: UsersService.usersControllerSaveConsent,
    onError: (error) => {
      console.log("🚀 ~ usePayments ~ error:", error);
    },
  });

  return {
    acceptWalletConsent,
    payments: payments ?? undefined,
    paymentsMethodLoading,
    getAssetsAPI,
    assets,
    isLoadingAsset,

    migrationPayments,
    getMigrationPaymentsAPI,
    isMigrationPaymentsAPILoading,
  };
}
