import { Menu, MenuItem } from '@mui/material';
import { useNavigate, useRouter } from '@tanstack/react-router';
import { t } from 'i18next';
import { FC } from 'react';
import Api from '../../../api/Api';
import { ROUTES } from '../../../types/Routes';
import LoginForm from '../../Forms/Login/LoginForm';

interface Props {
  anchorEl: HTMLElement | null;
  handleClose: () => void;
}

const UserMenu: FC<Props> = ({ anchorEl, handleClose }) => {
  const navigate = useNavigate();
  const router = useRouter();

  const user = Api.getAuthenticatedUser();

  return (
    <Menu
      anchorEl={anchorEl}
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'right',
      }}
      keepMounted
      transformOrigin={{
        vertical: 'top',
        horizontal: 'right',
      }}
      open={Boolean(anchorEl)}
      onClose={handleClose}
      sx={{
        '& .MuiMenu-paper': {
          minWidth: '240px',
        },
      }}
    >
      {user ? (
        [
          <MenuItem
            key="profile"
            onClick={() => {
              navigate({ to: ROUTES.PROFILE });
              handleClose();
            }}
          >
            {t('Profile')}
          </MenuItem>,
          <MenuItem
            key="logout"
            onClick={() => {
              Api.logOut();
              router.invalidate();
              handleClose();
            }}
          >
            {t('Log out')}
          </MenuItem>,
        ]
      ) : (
        <LoginForm handleClose={handleClose} />
      )}
    </Menu>
  );
};

export default UserMenu;
