"use client";
import { useEffect } from "react";
import { useGoogleLogin } from "@react-oauth/google";
import { ISession } from "@models/Session.model";
import ButtonSession from "@components/ButtonSession/ButtonSession";
import { loginByAndroid, loginByGoogle } from "@services/Session.Login";
import { useSessionStore, useSessionTokenStore } from "@store/Sesion.Store";
import { useConfirmStore } from "@core/Store/Confirm.Store";

export interface LoginGoogleProps {
    termsReaded: boolean;
}

export default function LoginGoogle(props: LoginGoogleProps) {
    const { termsReaded = false } = props;
    const SessionInfo = useSessionStore();
    const SessionToken = useSessionTokenStore();

    const confirm = useConfirmStore();

    useEffect(() => {
        // Add the event listener when the component mounts
        window.addEventListener("androidTokenReceived", handleAndroidToken);

        // Clean up the event listener when the component unmounts
        return () => {
            window.removeEventListener("androidTokenReceived", handleAndroidToken);
        };
    }, []);

    const handleAndroidToken = (event: Event) => {
        // Type assertion to access the 'detail' property of CustomEvent
        const customEvent = event as CustomEvent<string>;
        const token = customEvent.detail;

        loginByAndroid(token)
            .then((userSession: ISession) => {
                SessionInfo.setUser(userSession);
                SessionToken.setToken(userSession.userToken);
                SessionInfo.setLoginState("success");
            })
            .catch(() => {
                SessionInfo.clear();
                SessionToken.setToken("");
                SessionInfo.setLoginState("error");
            });
    };

    const login = useGoogleLogin({
        onSuccess: async (tokenResponse) => {
            loginByGoogle(tokenResponse.access_token)
                .then((userSession: ISession) => {
                    SessionInfo.setUser(userSession);
                    SessionToken.setToken(userSession.userToken);
                    SessionInfo.setLoginState("success");
                })
                .catch(() => {
                    SessionInfo.clear();
                    SessionToken.setToken("");
                    SessionInfo.setLoginState("error");
                });
        },
        onError: (error) => {
            console.error("Error durante la autenticación:", error);
        },
        scope: "profile",
    });

    return (
        <ButtonSession
            name="btnLoginGoogle"
            text="Continuar con Google"
            onClick={() => {
                if (!termsReaded) {
                    confirm.show(
                        "Para acceder con google debe aceptar los términos y condiciones y las politicas de privacidad",
                        () => { },
                        () => { }
                    );
                    return;
                }

                if (window.Android && typeof window.Android.startGoogleLogin === "function") {
                    window.Android.startGoogleLogin();
                    return;
                }

                login();
            }}
            type="submit"
            style={{ marginTop: "10px", width: "100%" }}
        />
    );
}
