import { ApplicaAuthProvider, AuthThirdPartyProviders } from '@applica-software-guru/iam-client';
import { Box, useTheme } from '@mui/material';
import { GoogleLogin } from '@react-oauth/google';
import { useAuthProvider, useNotify } from 'ra-core';
import { useNavigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { debounce } from 'lodash';

type GoogleLoginButtonProps = {
  setLoading: (loading: boolean) => void;
};

function GoogleLoginButton({ setLoading }: GoogleLoginButtonProps) {
  const theme = useTheme() as any;
  const isDark = theme.palette.mode === 'dark';
  const authProvider = useAuthProvider<ApplicaAuthProvider>();
  const notify = useNotify();
  const navigate = useNavigate();
  const [boxWidth, setBoxWidth] = useState<string | number>(395);
  const boxRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const debouncedUpdateButtonWidth = debounce(() => {
      if (boxRef?.current) {
        setBoxWidth(boxRef.current.offsetWidth);
      }
    }, 100);

    debouncedUpdateButtonWidth();
    window.addEventListener('resize', debouncedUpdateButtonWidth);

    return () => {
      window.removeEventListener('resize', debouncedUpdateButtonWidth);
      debouncedUpdateButtonWidth.cancel();
    };
  }, [boxRef]);

  function handleSuccess(response: any) {
    setLoading(true);
    authProvider
      .thirdPartyLogin({ provider: AuthThirdPartyProviders.GOOGLE, payload: { credential: response.credential } })
      .then(() => {
        setLoading(false);
        navigate('/');
      })
      .catch((error: any) => {
        setLoading(false);
        notify(
          typeof error === 'string'
            ? error
            : typeof error === 'undefined' || !error.message
            ? 'ra.auth.sign_in_error'
            : error.message,
          {
            type: 'error',
            messageArgs: {
              _: typeof error === 'string' ? error : error && error.message ? error.message : undefined
            }
          }
        );
      });
  }

  function handleError() {
    notify('ra.auth.sign_in_error', {
      type: 'error'
    });
  }
  return (
    <Box sx={{ colorScheme: isDark ? 'light' : 'dark', width: '100%' }} ref={boxRef}>
      <GoogleLogin theme="outline" width={boxWidth} onSuccess={handleSuccess} onError={handleError} />
    </Box>
  );
}

export { GoogleLoginButton };
