import { ONBOARDING_POSITION, ONBOARDING_STEPS } from "@/configs";
import { storage } from "@/configs/storage";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { AppConfig } from "@/types/app_config";
import { User } from "@/types/user";
import { UseMutateFunction } from "@tanstack/react-query";
import { AxiosResponse } from "axios";
import { useMemo } from "react";
import { useQueryMutation } from "./mutate/useQueryMutation";

type useAuthHandlerTypes = {
  authConfig: {
    is_phone_enabled: boolean;
    is_email_enabled: boolean;
    is_kyc_enabled: boolean;
    is_agreement_enabled: boolean;
  };
  sendOTP: UseMutateFunction<
    AxiosResponse<any, any>,
    any,
    {
      [key: string]: any;
    },
    unknown
  >;
  verifyOTP: UseMutateFunction<
    AxiosResponse<any, any>,
    any,
    {
      [key: string]: any;
    },
    unknown
  >;
  signInWith2fa: UseMutateFunction<
    AxiosResponse<any, any>,
    any,
    {
      [key: string]: any;
    },
    unknown
  >;
  signInWith2faLoading: boolean;
  otpSendLoading: boolean;
  verifyLoading: boolean;
  redirect: (user: User) => Promise<string | undefined>;
  setKycWaitingStep: () => Promise<void>;
  setOtpBreakTimer: (otp_expire_key: string) => Promise<void>;
  sendOTPError: any;
  verifyOTPError: any;
  signInWith2faError: any;
};
export const useAuthHandler = () => {
  const { appInfo }: { appInfo: AppConfig } = useAuthStore((state) => state);

  const authConfig = useMemo(() => {
    return {
      recaptcha: appInfo?.extensions?.recaptcha,
      is_phone_enabled: appInfo?.service_switch?.system_config?.phone_verification?.is_enabled ?? appInfo?.application_info?.extra_service?.system_config?.phone_verification?.is_enabled ?? false,
      is_email_enabled: appInfo?.service_switch?.system_config?.email_verification?.is_enabled ?? appInfo?.application_info?.extra_service?.system_config?.email_verification?.is_enabled ?? false,
      is_kyc_enabled: appInfo?.service_switch?.system_config?.kyc_verification?.is_enabled ?? appInfo?.application_info?.extra_service?.system_config?.kyc_verification?.is_enabled ?? false,
      is_agreement_enabled: appInfo?.service_switch?.system_config?.agreement_terms_and_policy?.is_enabled ?? appInfo?.application_info?.extra_service?.system_config?.agreement_terms_and_policy?.is_enabled ?? false,
    };
  }, [appInfo]);

  const {
    mutate: sendOTP,
    isLoading: otpSendLoading,
    backendErrors: sendOTPError,
  } = useQueryMutation({
    isPublic: true,
    url: "/send-otp",
  });

  const {
    mutate: verifyOTP,
    isLoading: verifyLoading,
    backendErrors: verifyOTPError,
  } = useQueryMutation({
    isPublic: true,
    url: "/verify-email-or-phone",
  });

  const {
    mutate: signInWith2fa,
    isLoading: signInWith2faLoading,
    backendErrors: signInWith2faError,
  } = useQueryMutation({
    isPublic: true,
    url: "/two-factor-login",
  });

  // ⏳ Save OTP expiration timestamp in storage
  const setOtpBreakTimer = async (otp_expire_key: string) => {
    try {
      const breakTime = Number(appInfo?.application_info?.otp?.expire_time || 2) * 60;
      const newExpiry = Date.now() + breakTime * 1000;
      storage.set(otp_expire_key, newExpiry.toString());
    } catch (error) {
      console.error("Error setting OTP break timer:", error);
    }
  };

  const redirect = async (user: User): Promise<string | undefined> => {
    try {
      const signInCount = storage.getString("sign_in_count");
      const onboardingPosition = storage.getString(ONBOARDING_POSITION);
      const { is_email_enabled, is_phone_enabled, is_kyc_enabled } = authConfig;

      // Step 1: Email/Phone verification check
      const needsEmailVerification = is_email_enabled && !user?.email_verified_at;
      const needsPhoneVerification = is_phone_enabled && !user?.phone_verified_at;
      const isKycVerified = user?.is_kyc_verified || user?.kyc_status === "approved";

      const isPastVerificationStep =
        onboardingPosition === ONBOARDING_STEPS.kyc.value || onboardingPosition === ONBOARDING_STEPS.waiting.value || onboardingPosition === ONBOARDING_STEPS.completed.value;

      if (!isPastVerificationStep && (needsEmailVerification || needsPhoneVerification)) {
        storage.set(ONBOARDING_POSITION, ONBOARDING_STEPS.verification.value);

        if (needsEmailVerification) {
          return `/verify-email-mobile?email=${user?.email}`;
        }
        if (needsPhoneVerification && user?.phone) {
          return `/verify-email-mobile?phone=${user?.phone}`;
        }
      }

      console.log({is_kyc_enabled, isKycVerified});

      // Step 2: KYC rejected or never submitted → go to KYC form
      if (is_kyc_enabled && !isKycVerified && (!user?.kyc_status || user?.kyc_status === "rejected")) {
        storage.set(ONBOARDING_POSITION, ONBOARDING_STEPS.kyc.value);
        return "/kyc";
      }
      // Step 3: KYC pending → go to waiting
      if (is_kyc_enabled && !isKycVerified && user?.kyc_status === "pending") {
        storage.set(ONBOARDING_POSITION, ONBOARDING_STEPS.waiting.value);
        return "/waiting";
      }

      // Step 4: KYC enabled but still not verified and onboarding position is waiting
      if (is_kyc_enabled && !isKycVerified && onboardingPosition === ONBOARDING_STEPS.waiting.value) {
        return "/waiting";
      }

      // Step 5: All checks passed → go to app
      storage.set(ONBOARDING_POSITION, ONBOARDING_STEPS.completed.value);

      if (user?.phone_verified_at) {
        if (signInCount === "2") {
          storage.remove("sign_in_count");
        } else {
          storage.set("sign_in_count", "1");
        }
      }

      const finalPath = "/(tabs)";
      console.log(`[useAuthHandler] Redirect logic finished. Result: ${finalPath}`);
      return finalPath;
    } catch (error) {
      console.error("Error in redirect logic:", error);
      return undefined;
    }
  };

  const setKycWaitingStep = async () => {
    try {
      storage.set(ONBOARDING_POSITION, ONBOARDING_STEPS.waiting.value);
    } catch (error) {
      console.error("Error setting KYC waiting step:", error);
    }
  };

  return {
    authConfig,
    sendOTP,
    sendOTPError,
    verifyOTP,
    verifyOTPError,
    otpSendLoading,
    verifyLoading,
    redirect,
    setKycWaitingStep,
    setOtpBreakTimer,
    signInWith2fa,
    signInWith2faLoading,
    signInWith2faError,
  } as useAuthHandlerTypes;
};
