import { AuthService } from "../services/authServices";
import { useAuthStore } from "../stores/authStore";

interface UsePhoneAuthReturn {
  sendOTP: (phoneNumber: string) => Promise<void>;
  verifyOTP: (code: string) => Promise<void>;
  loading: boolean;
  error: string | null;
  confirmationResult: any | null;
}

export const usePhoneAuth = (): UsePhoneAuthReturn => {
  const {
    phoneConfirmationResult: confirmationResult,
    phoneLoading: loading,
    phoneError: error,
    setPhoneConfirmationResult: setConfirmationResult,
    setPhoneLoading: setLoading,
    setPhoneError: setError,
    setUser,
  } = useAuthStore();

  const sendOTP = async (phoneNumber: string) => {
    setLoading(true);
    setError(null);

    try {
      console.log(
        "usePhoneAuth: Calling AuthService.sendOTP with:",
        phoneNumber
      );
      const result = await AuthService.sendOTP(phoneNumber);
      console.log("usePhoneAuth: Result from AuthService.sendOTP:", result);

      if (result.error) {
        console.log("usePhoneAuth: Setting error:", result.error);
        setError(result.error);
      } else if (result.confirmationResult) {
        console.log("usePhoneAuth: Setting confirmationResult");
        setConfirmationResult(result.confirmationResult);
      } else {
        console.log("usePhoneAuth: No confirmationResult found in result");
      }
    } catch (err) {
      console.log("usePhoneAuth: Caught error:", err);
      setError(err instanceof Error ? err.message : "Failed to send OTP");
    } finally {
      setLoading(false);
    }
  };

  const verifyOTP = async (code: string) => {
    const isDevBypass = __DEV__;

    if (!confirmationResult && !isDevBypass) {
      setError("No verification session found. Please request OTP first.");
      return;
    }

    setLoading(true);
    setError(null);

    try {
      let userCredential: any;

      if (isDevBypass) {
        console.log("usePhoneAuth: Using DEV OTP bypass (no Firebase call)");
        const devUser = {
          uid: "dev-emulator-user",
          phoneNumber: "DEV",
        };
        userCredential = { user: devUser };
      } else {
        console.log("usePhoneAuth: Verifying OTP with native Firebase");
        userCredential = await confirmationResult.confirm(code);
      }

      if (userCredential?.user) {
        setUser(userCredential.user);
      }

      console.log(
        "usePhoneAuth: OTP verified successfully, user:",
        userCredential?.user?.uid
      );
    } catch (err: any) {
      console.error("usePhoneAuth: OTP verification failed:", err);
      setError(err?.message || "Invalid verification code");
    } finally {
      setLoading(false);
    }
  };

  return {
    sendOTP,
    verifyOTP,
    loading,
    error,
    confirmationResult,
  };
};

// Re-export the auth store hook for convenience
export const useAuthState = () => {
  const {
    user,
    loading,
    profile,
    wallet,
    profileLoading,
    walletLoading,
    profileError,
    walletError,
    formattedBalance,
  } = useAuthStore();
  return {
    user,
    loading,
    profile,
    wallet,
    profileLoading,
    walletLoading,
    profileError,
    walletError,
    formattedBalance,
  };
};
