import { useEffect, useRef } from 'react';
import type {
  LoginOrSignUpWithGoogleRequest,
  LoginResult,
} from '../../types/userTypes';
import type { AuthFactory } from '../../types/authTypes';
import {
  generateTokenWithGoogle,
  type GenerateTokenResponse,
} from '../../api/identityAPI';
import { loginOrSignUpWithGoogle } from '../../api/authorizationAPI';
import { useApi } from '@/hooks/useApi';
import { Icon, useToast } from '@rkheftan/harmony-ui';
import { useTranslation } from 'react-i18next';
import { Box, Button } from '@mui/material';
import { Google } from 'iconsax-react';

interface GoogleAuthenticationV2Props {
  disabled: boolean;
  authFactory: AuthFactory;
  onGoogleAuthenticated: (
    loginResult: LoginResult,
    tokenResponse: GenerateTokenResponse,
  ) => void;
}

export const GoogleAuthenticationV2 = ({
  disabled,
  authFactory,
  onGoogleAuthenticated,
}: GoogleAuthenticationV2Props) => {
  const toast = useToast();
  const { t } = useTranslation('authentication');
  const { loading: loginWithGoogleLoading, execute: loginWithGoogleCall } =
    useApi(loginOrSignUpWithGoogle);
  const googleButtonRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const initializeData = {
      client_id: import.meta.env.VITE_GOOGLE_CLIENT_ID,
      callback: handleCredentialResponse,
    };

    google.accounts.id.initialize(initializeData);

    google.accounts.id.renderButton(
      document.getElementById('google-signin-button'),
      { theme: 'outline' },
    );
  }, []);

  const handleCredentialResponse = async (response: { credential: any }) => {
    const idToken = response.credential;

    try {
      const apiRequest: LoginOrSignUpWithGoogleRequest = {
        idToken: idToken,
        returnUrl: authFactory.redirectUrl,
      };
      const res = await loginWithGoogleCall(apiRequest);

      if (!res) return;

      if (res.success) {
        const tokenRes = await generateTokenWithGoogle({
          ...apiRequest,
          client_id: authFactory.clientId,
        });

        onGoogleAuthenticated(res, tokenRes.data);
      } else {
        toast({
          message: t('loginForm.googleAuthenticationFailed'),
          severity: 'error',
        });
      }
    } catch (error) {
      toast({
        message: t('loginForm.googleAuthenticationFailed'),
        severity: 'error',
      });
    }
  };

  const handleGoogleLogin = () => {
    if (googleButtonRef.current) {
      const googleCustomRenderedDivs =
        googleButtonRef.current.querySelectorAll('div');

      googleCustomRenderedDivs.forEach((b) => b.click());
    }
  };

  return (
    <>
      <Box sx={{ display: 'none !important' }}>
        <div ref={googleButtonRef} id="google-signin-button"></div>
      </Box>

      <Button
        type="button"
        onClick={handleGoogleLogin}
        disabled={disabled}
        loading={loginWithGoogleLoading}
        variant="outlined"
        startIcon={<Icon Component={Google} variant="Bold" />}
      >
        {t('loginForm.loginWithGoogle')}
      </Button>
    </>
  );
};
