import { Menu, MenuItem } from '@mui/material';
import { useMatch, 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 match = useMatch({ from: '/profile/', strict: true, shouldThrow: false });

  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
            selected={!!match}
            key="profile"
            onClick={() => {
              navigate({ to: ROUTES.PROFILE });
              handleClose();
            }}
          >
            {t('Profile')}
          </MenuItem>,
          <MenuItem
            key="logout"
            onClick={async () => {
              await Api.logOut();
              router.invalidate();
              handleClose();
            }}
          >
            {t('Log out')}
          </MenuItem>,
        ]
      ) : (
        <LoginForm handleClose={handleClose} />
      )}
    </Menu>
  );
};

export default UserMenu;
