import {
  Avatar,
  Box,
  IconButton,
  ListItemIcon,
  ListItemText,
  Menu,
  MenuItem,
  Typography,
} from '@mui/material';
import { Icon } from '@rkheftan/harmony-ui';
import { Logout, More } from 'iconsax-react';
import type { UserInfo } from '@/contexts/AuthContext';
import { LTRTypography } from '../common/LTRTypography';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/hooks/useAuth';
import { FlexBox } from '../common/FlexBox';

interface HeaderProps {
  user: UserInfo;
}

export const Header: React.FC<HeaderProps> = ({ user }) => {
  const { t, i18n } = useTranslation('sideNav');

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const { logout } = useAuth();

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = () => {
    handleClose();
    logout();
  };

  return (
    <>
      <Box
        sx={{
          p: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          height: (t) => t.spacing(10.5),
        }}
      >
        <FlexBox sx={{ alignItems: 'center', gap: 1 }}>
          <Avatar
            sx={{ width: 32, height: 32, fontSize: '14px' }}
            src={user.picture}
          >
            {user.firstName.charAt(0) + ' ' + user.lastName.charAt(0)}
          </Avatar>
          <Box>
            <Typography variant="body1" color="textSecondary">
              {user.fullName}
            </Typography>
            {/* TODO: add ternary text color to palette */}
            <LTRTypography variant="body2" color="#757575">
              {user.phoneNumber ?? user.email}
            </LTRTypography>
          </Box>
        </FlexBox>

        <IconButton onClick={handleClick} color="primary">
          <Icon Component={More} />
        </IconButton>
      </Box>
      <Menu
        id="account-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: i18n.dir() === 'rtl' ? 'right' : 'left',
        }}
      >
        <MenuItem
          sx={{
            color: 'error.main',
            '& .MuiListItemIcon-root': {
              color: 'error.main',
            },
          }}
          onClick={handleLogout}
        >
          <ListItemIcon>
            <Icon Component={Logout} />
          </ListItemIcon>
          <ListItemText>{t('header.logout')}</ListItemText>
        </MenuItem>
      </Menu>
    </>
  );
};
