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

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

/**
 * @deprecated use V2 instead
 */
export const GoogleAuthentication = ({
  disabled,
  authFactory,
  onGoogleAuthenticated,
}: GoogleAuthenticationProps) => {
  const { t } = useTranslation('authentication');
  const { loading: loginWithGoogleLoading, execute: loginWithGoogleCall } =
    useApi(loginOrSignUpWithGoogle);
  const toast = useToast();
  const clientRef = useRef<any>(null);

  useEffect(() => {
    const script = document.createElement('script');
    script.src = 'https://accounts.google.com/gsi/client';
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);

    script.onload = () => {
      clientRef.current = google.accounts.id.initialize({
        client_id: import.meta.env.VITE_GOOGLE_CLIENT_ID,
        callback: async (resp: GoogleCodeClientResponse) => {
          const apiRequest: LoginOrSignUpWithGoogleRequest = {
            idToken: resp.id_token,
            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',
            });
          }
        },
      });
    };

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  const handleGoogleLogin = () => {
    if (clientRef.current) {
      clientRef.current.requestCode();
    }
  };

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