import { LogoutOutlined } from '@mui/icons-material';
import { ListItemButton, ListItemIcon, ListItemText } from '@mui/material';
import { useAuthProvider, useTranslate } from 'ra-core';
import { useCallback, useEffect, useState } from 'react';

function StopImpersonateButton(): JSX.Element | null {
  const translate = useTranslate();
  const authProvider = useAuthProvider();
  const stopImpersonating = useCallback(
    () => authProvider.stopImpersonate().then(() => (document.location.href = '/')),
    [authProvider]
  );
  const [isImpersonating, setIsImpersonating] = useState(false);

  useEffect(() => {
    if (!authProvider.isImpersonating) {
      // eslint-disable-next-line no-console
      console.warn('The authProvider does not support the isImpersonating feature', authProvider);
      return;
    }
    authProvider.isImpersonating().then((isImpersonating: boolean) => setIsImpersonating(isImpersonating));
  }, [authProvider, setIsImpersonating]);

  if (!isImpersonating) {
    return null;
  }

  return (
    <>
      <ListItemButton onClick={stopImpersonating}>
        <ListItemIcon>
          <LogoutOutlined />
        </ListItemIcon>
        <ListItemText primary={translate('ra.auth.stop_impersonate')} />
      </ListItemButton>
    </>
  );
}

export { StopImpersonateButton };
