import { Button } from '@mui/material';
import { Google } from 'iconsax-reactjs';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { GoogleCodeClientResponse } from '../../types/userTypes';
import { loginOrSignUpWithGoogle } from '../../api/authorizationAPI';
import type { GUID } from '@/types/commonTypes';

declare global {
  interface Window {
    google: typeof google;
  }
  const google: any;
}

export interface GoogleAuthenticationProps {
  disabled: boolean;
  authReturnUrl: string;
  onGoogleAuthenticated: (userId: GUID) => void;
}

export const GoogleAuthentication = ({
  disabled,
  authReturnUrl,
  onGoogleAuthenticated,
}: GoogleAuthenticationProps) => {
  const { t } = useTranslation('authentication');
  const [loginWithGoogleLoading, setLoginWithGoogleLoading] =
    useState<boolean>(false);

  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.oauth2.initCodeClient({
        client_id: 'CLIEND_ID',
        scope: 'openid email profile',
        ux_mode: 'popup',
        response_type: 'id_token',
        callback: async (resp: GoogleCodeClientResponse) => {
          setLoginWithGoogleLoading(true);

          const result = await loginOrSignUpWithGoogle({
            idToken: resp.id_token,
            returnUrl: authReturnUrl,
          });
          const jsonRes = await result.json();

          if (jsonRes.success) {
            onGoogleAuthenticated(jsonRes.userId);
          } else {
            handleGoogleLogin();
          }

          setLoginWithGoogleLoading(false);
        },
      });
    };
  }, []);

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

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