import { useState } from 'react'
import PersonIcon from '@mui/icons-material/Person'
import IconButton from '@mui/material/IconButton'
import ListItemText from '@mui/material/ListItemText'
import Menu from '@mui/material/Menu'
import MenuItem from '@mui/material/MenuItem'
import type { AuthUser } from '@/shared/model/auth'
import { UserAvatar } from '@/shared/ui/UserAvatar'

type Props = {
  user: AuthUser | null
  isAdmin?: boolean
  onNavigate: (to: string) => void
  onLogout: () => void
}

export function UserMenu({ user, isAdmin = false, onNavigate, onLogout }: Props) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)

  const openMenu = (e: React.MouseEvent<HTMLElement>) => setAnchorEl(e.currentTarget)
  const closeMenu = () => setAnchorEl(null)

  const go = (to: string) => {
    closeMenu()
    onNavigate(to)
  }

  const handleLogout = () => {
    closeMenu()
    onLogout()
  }

  return (
    <>
      <IconButton
        color="inherit"
        onClick={user ? openMenu : () => go('/auth')}
        sx={{ ml: 1 }}
        aria-label="Пользователь"
      >
        {user ? (
          <UserAvatar userId={user.id} avatarUrl={user.avatar} avatarStyle={user.avatarStyle} size={28} />
        ) : (
          <PersonIcon sx={{ fontSize: 28 }} />
        )}
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={closeMenu}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        {user ? (
          <>
            <MenuItem onClick={() => go(isAdmin ? '/admin/settings' : '/me')}>
              <ListItemText
                primary={(user.displayName && user.displayName.trim()) || user.email}
                secondary={isAdmin ? 'Настройки' : 'Профиль'}
              />
            </MenuItem>
            <MenuItem onClick={handleLogout}>Выход</MenuItem>
          </>
        ) : (
          <MenuItem onClick={() => go('/auth')}>Войти / регистрация</MenuItem>
        )}
      </Menu>
    </>
  )
}
