import * as Google from "expo-auth-session/providers/google";
import { router } from "expo-router";
import { useCallback, useEffect } from "react";
import { Image, Text, View, Alert } from "react-native";
import { icons } from "@/constants";
import { googleAuth } from "@/lib/auth";
import { useSession } from "@/lib/session";
import { CustomButton } from "./custom-button";
type OAuthProps = {
title: string;
};
export const OAuth = ({ title }: OAuthProps) => {
const clientId = process.env.EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID;
const iosClientId = process.env.EXPO_PUBLIC_GOOGLE_AUTH_IOS_CLIENT_ID;
const androidClientId =
process.env.EXPO_PUBLIC_GOOGLE_AUTH_ANDROID_CLIENT_ID;
const isConfigured = Boolean(
clientId && (androidClientId || iosClientId),
);
if (!isConfigured) return null;
return ;
};
function GoogleOAuth({
title,
clientId,
iosClientId,
androidClientId,
}: OAuthProps & {
clientId: string;
iosClientId?: string;
androidClientId?: string;
}) {
const { setSession } = useSession();
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId,
iosClientId,
androidClientId,
});
useEffect(() => {
if (response?.type !== "success") return;
const idToken = response.params?.id_token;
if (!idToken) {
Alert.alert("Google sign-in failed", "No token returned. Try again.");
return;
}
void (async () => {
try {
await setSession(await googleAuth(idToken));
router.replace("/");
} catch (err: any) {
console.error("OAuth error", err);
Alert.alert(
"Google sign-in failed",
err?.message || "Please try again.",
);
}
})();
}, [response, setSession]);
const handleGoogleOAuth = useCallback(() => {
void promptAsync();
}, [promptAsync]);
return (
Or
(
)}
bgVariant="outline"
textVariant="primary"
onPress={handleGoogleOAuth}
disabled={!request}
/>
);
}