import { useState } from 'react'
import Badge from '@mui/material/Badge'
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 { User } from 'lucide-react'
import type { AuthUser } from '@/shared/model/auth'

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

export function UserMenu({ user, 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={openMenu} sx={{ ml: 1 }} aria-label="Пользователь">
        <Badge
          variant="dot"
          color="success"
          overlap="circular"
          invisible={!user}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        >
          <User />
        </Badge>
      </IconButton>

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