import { useMutation } from "@tanstack/react-query";
import type { AxiosResponse } from "axios";
import { toast } from "sonner";
import {
  registerTradeLicense,
  setETradePassword,
  SetETradePasswordPayload,
  TradeLicensePayload,
  verifyEtradeOtpCode,
} from "../services/portalOutgoingService";
import type { VerifyEtradeOtpPayload } from "@/shared/services/authService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";

export const useTradeLicenseVerification = () => {
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const registerMutation = useMutation<AxiosResponse, unknown, TradeLicensePayload>(
    {
      mutationFn: (body) => registerTradeLicense(body),
      onSuccess: () => {
        toast.success(t("registration.etrade.otpSent"));
      },
      onError: (error) => {
        if (
          error instanceof Error &&
          error.message === "ETRADE_PHONE_LOOKUP_FAILED"
        ) {
          toast.error(t("registration.etrade.phoneLookupFailed"));
          return;
        }
        handleError(error);
      },
    },
  );

  const verifyOtpMutation = useMutation<
    AxiosResponse,
    unknown,
    VerifyEtradeOtpPayload
  >({
    mutationFn: (body) => verifyEtradeOtpCode(body),
    onSuccess: () => {
      toast.success(t("registration.etrade.registrationSuccess"));
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const passwordMutation = useMutation<
    AxiosResponse,
    unknown,
    SetETradePasswordPayload
  >({
    mutationFn: (body) => setETradePassword(body),
    onSuccess: () => {
      toast.success("Password set successfully");
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    registerTradeLicense: registerMutation.mutateAsync,
    verifyEtradeOtp: verifyOtpMutation.mutateAsync,
    setETradePassword: passwordMutation.mutateAsync,
    isRegistering: registerMutation.isPending,
    isVerifyingOtp: verifyOtpMutation.isPending,
    isSettingPassword: passwordMutation.isPending,
    registerResponse: registerMutation.data,
    verifyOtpResponse: verifyOtpMutation.data,
    passwordResponse: passwordMutation.data,
  };
};
