import { useState } from 'react'
import { useNavigate } from 'react-router'
import { Avatar, Box, Divider, IconButton, ListItemIcon, Menu, MenuItem, Typography } from '@mui/material'
import { HelpCircle, LogOut, Settings, User } from 'lucide-react'
import { useSessionStore } from '../../stores/sessionStore'
import { useToastStore } from '../../stores/toastStore'
import { DemoRoleSwitcher } from '../auth/DemoRoleSwitcher'

const ROLE_LABELS: Record<string, string> = {
  PROPERTY_MANAGER: 'Property Manager',
  DEMAND_USER: 'Demand User',
}

function getUserInitials(name: string): string {
  return name
    .split(' ')
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2)
}

export function UserMenu() {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const { currentUser, logout } = useSessionStore()
  const navigate = useNavigate()
  const showToast = useToastStore((s) => s.showToast)

  function handleOpen(e: React.MouseEvent<HTMLElement>) {
    setAnchorEl(e.currentTarget)
  }

  function handleClose() {
    setAnchorEl(null)
  }

  function handleLogout() {
    handleClose()
    logout()
    navigate('/auth/login')
  }

  const initials = getUserInitials(currentUser?.name ?? 'U')

  return (
    <>
      <IconButton onClick={handleOpen} size="small" sx={{ p: 0 }}>
        <Avatar sx={{ width: 32, height: 32, fontSize: '0.75rem', bgcolor: '#152642' }}>
          {initials}
        </Avatar>
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={!!anchorEl}
        onClose={handleClose}
        slotProps={{ paper: { sx: { width: 300, mt: 1 } } }}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        {/* User info header */}
        {currentUser && (
          <Box sx={{ px: 2, py: 1.5 }}>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>{currentUser.name}</Typography>
            <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>
              {ROLE_LABELS[currentUser.role] ?? currentUser.role}
            </Typography>
            <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>
              {currentUser.organizationName}
            </Typography>
          </Box>
        )}

        <Divider />

        <MenuItem onClick={() => { handleClose(); showToast('Profilseite ist in Kürze verfügbar.', 'info') }}>
          <ListItemIcon><User size={16} /></ListItemIcon>
          Profil
        </MenuItem>
        <MenuItem onClick={() => { handleClose(); showToast('Einstellungen sind in Kürze verfügbar.', 'info') }}>
          <ListItemIcon><Settings size={16} /></ListItemIcon>
          Einstellungen
        </MenuItem>
        <MenuItem onClick={() => { handleClose(); localStorage.removeItem('property_match_welcomed'); window.location.reload() }}>
          <ListItemIcon><HelpCircle size={16} /></ListItemIcon>
          Produkttour starten
        </MenuItem>

        <Divider />

        {/* Demo role switcher */}
        <Box sx={{ px: 1, py: 1 }}>
          <DemoRoleSwitcher />
        </Box>

        <Divider />

        <MenuItem onClick={handleLogout}>
          <ListItemIcon><LogOut size={16} /></ListItemIcon>
          Abmelden
        </MenuItem>
      </Menu>
    </>
  )
}
