import { Box, Link, Menu, MenuItem, Typography } from '@mui/material';
import { useMatch, useNavigate, useRouter } from '@tanstack/react-router';
import { t } from 'i18next';
import { FC, useState } from 'react';
import { Trans } from 'react-i18next/TransWithoutContext';
import { useApi } from '../../../api/Api';
import { ROUTES } from '../../../types/Routes';
import RegisterDialog from '../../Dialogs/Register/RegisterDialog';
import LoginForm from '../../Forms/Login/LoginForm';

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

const UserMenu: FC<Props> = ({ anchorEl, handleClose }) => {
  const [register, setRegister] = useState(false);

  const navigate = useNavigate();
  const router = useRouter();
  const match = useMatch({ from: '/profile/', strict: true, shouldThrow: false });

  const Api = useApi();

  const _handleClose = () => {
    setRegister(false);
    handleClose();
  };

  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',
        },
      }}
    >
      {Api.authenticatedUser ? (
        [
          <MenuItem
            selected={!!match}
            key="profile"
            onClick={() => {
              navigate({ to: ROUTES.PROFILE });
              _handleClose();
            }}
          >
            {t('Profile')}
          </MenuItem>,
          <MenuItem
            key="logout"
            onClick={async () => {
              await Api.logOut();
              router.invalidate();
              navigate({ to: ROUTES.INDEX });
            }}
          >
            {t('Log out')}
          </MenuItem>,
        ]
      ) : register ? (
        <RegisterDialog open={register} onClose={() => setRegister(false)} />
      ) : (
        <Box>
          <LoginForm />
          <Box sx={{ padding: 1 }}>
            <Trans i18nKey="Register prompt">
              <Typography component="span" />
              <Link
                sx={{ cursor: 'pointer' }}
                variant="body1"
                underline="hover"
                color="secondary.main"
                onClick={() => {
                  setRegister(true);
                  handleClose();
                }}
              />
              <Typography component="span" />
            </Trans>
          </Box>
        </Box>
      )}
    </Menu>
  );
};

export default UserMenu;
