import { Box, Typography, Avatar, IconButton, Tooltip } from '@mui/material'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { NavLink } from 'react-router'
import { WorkspaceType } from '../../domain/enums'
import { useCompareStore } from '../../stores/compareStore'
import { WORKSPACE_CONFIG, WORKSPACE_ORDER, getUserInitials } from './appShellConfig'

// ---------------------------------------------------------------------------
// Visual constants
// ---------------------------------------------------------------------------

export const SIDEBAR_BG = '#0f1923'
export const DIVIDER_COLOR = 'rgba(255,255,255,0.08)'
export const TEXT_MUTED = '#94a3b8'
export const TEXT_WHITE = '#ffffff'
export const NAV_ACTIVE_BG = 'transparent'
export const NAV_ACTIVE_ACCENT = '#b8975a'
export const NAV_HOVER_BG = 'rgba(255,255,255,0.06)'

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface SidebarProps {
  collapsed: boolean
  activeWorkspace: WorkspaceType
  allowedWorkspaces: WorkspaceType[]
  onWorkspaceClick: (workspace: WorkspaceType) => void
  onToggle: () => void
  onClose?: () => void
  userName: string
  orgName: string
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function Sidebar({
  collapsed,
  activeWorkspace,
  allowedWorkspaces,
  onWorkspaceClick,
  onToggle,
  onClose,
  userName,
  orgName,
}: SidebarProps) {
  const config = WORKSPACE_CONFIG[activeWorkspace]
  const compareCount = useCompareStore(s => s.compareItems.length)
  const width = collapsed ? 60 : 264
  const visibleWorkspaces = WORKSPACE_ORDER.filter((ws) => allowedWorkspaces.includes(ws))

  return (
    <Box
      component="nav"
      sx={{
        width,
        minWidth: width,
        flexShrink: 0,
        height: '100vh',
        backgroundColor: SIDEBAR_BG,
        display: 'flex',
        flexDirection: 'column',
        transition: 'width 0.2s ease',
        overflow: 'hidden',
      }}
    >
      {/* Logo area */}
      <Box
        sx={{
          height: 56,
          display: 'flex',
          alignItems: 'center',
          justifyContent: collapsed ? 'center' : 'flex-start',
          px: collapsed ? 0 : 2.5,
          borderBottom: `1px solid ${DIVIDER_COLOR}`,
          flexShrink: 0,
        }}
      >
        {collapsed ? (
          <Typography
            variant="subtitle1"
            sx={{ color: TEXT_WHITE, fontWeight: 700, letterSpacing: 0.5 }}
          >
            PM
          </Typography>
        ) : (
          <Box>
            <Typography
              variant="subtitle1"
              sx={{ color: TEXT_WHITE, fontWeight: 700, lineHeight: 1.2 }}
            >
              Property
            </Typography>
            <Typography
              variant="caption"
              sx={{
                color: '#64b5f6',
                fontWeight: 600,
                textTransform: 'uppercase',
                letterSpacing: 1,
                fontSize: '0.6rem',
              }}
            >
              Match
            </Typography>
          </Box>
        )}
      </Box>

      {/* Workspace tabs — side-by-side segmented control (hidden when only 1 workspace) */}
      {visibleWorkspaces.length > 1 && <Box
        sx={{
          borderBottom: `1px solid ${DIVIDER_COLOR}`,
          display: 'grid',
          gridTemplateColumns: collapsed ? '1fr' : `repeat(${visibleWorkspaces.length}, 1fr)`,
          flexShrink: 0,
        }}
      >
        {visibleWorkspaces.map((ws, idx) => {
          const wsConfig = WORKSPACE_CONFIG[ws]
          const Icon = wsConfig.icon
          const isActive = ws === activeWorkspace

          const tabContent = (
            <Box
              onClick={() => { onWorkspaceClick(ws); onClose?.() }}
              sx={{
                display: 'flex',
                flexDirection: collapsed ? 'row' : 'column',
                alignItems: 'center',
                justifyContent: 'center',
                gap: collapsed ? 0 : 0.5,
                py: collapsed ? 1 : 1.25,
                cursor: 'pointer',
                backgroundColor: isActive ? wsConfig.chipColor : 'transparent',
                borderRight: !collapsed && idx < visibleWorkspaces.length - 1
                  ? `1px solid ${DIVIDER_COLOR}`
                  : 'none',
                transition: 'background-color 0.15s ease',
                '&:hover': {
                  backgroundColor: isActive ? wsConfig.chipColor : NAV_HOVER_BG,
                },
              }}
            >
              <Icon size={15} color={isActive ? TEXT_WHITE : TEXT_MUTED} />
              {!collapsed && (
                <Typography
                  variant="caption"
                  sx={{
                    color: isActive ? TEXT_WHITE : TEXT_MUTED,
                    fontWeight: isActive ? 700 : 400,
                    fontSize: '0.6875rem',
                    lineHeight: 1,
                    letterSpacing: 0.2,
                  }}
                >
                  {wsConfig.label}
                </Typography>
              )}
            </Box>
          )

          return collapsed ? (
            <Tooltip key={ws} title={wsConfig.label} placement="right">
              {tabContent}
            </Tooltip>
          ) : (
            <Box key={ws}>{tabContent}</Box>
          )
        })}
      </Box>}

      {/* Nav items */}
      <Box sx={{ flex: 1, overflowY: 'auto', py: 0.5 }}>
        {config.navItems.map((item) => {
          const Icon = item.icon

          const navContent = (
            <NavLink
              to={item.path}
              style={{ textDecoration: 'none', display: 'block' }}
              onClick={() => onClose?.()}
            >
              {({ isActive }) => (
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 1.25,
                    pl: collapsed ? 0 : isActive ? 1.25 : 1.5,
                    pr: collapsed ? 0 : 1.5,
                    py: 0.75,
                    mx: 0.5,
                    borderRadius: 1,
                    justifyContent: collapsed ? 'center' : 'flex-start',
                    borderLeft: collapsed ? 'none' : `3px solid ${isActive ? NAV_ACTIVE_ACCENT : 'transparent'}`,
                    backgroundColor: 'transparent',
                    '&:hover': { backgroundColor: NAV_HOVER_BG },
                    transition: 'border-color 0.15s ease',
                    cursor: 'pointer',
                  }}
                >
                  <Icon size={16} color={isActive ? TEXT_WHITE : TEXT_MUTED} />
                  {!collapsed && (
                    <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', gap: 0.75, minWidth: 0 }}>
                      <Typography
                        variant="body2"
                        sx={{
                          color: isActive ? TEXT_WHITE : TEXT_MUTED,
                          fontWeight: isActive ? 600 : 400,
                          fontSize: '0.875rem',
                          letterSpacing: '-0.01em',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {item.label}
                      </Typography>
                      {item.path === '/demand/compare' && compareCount > 0 && (
                        <Box sx={{
                          minWidth: 18, height: 18, borderRadius: '9px',
                          bgcolor: '#d97706', color: 'white',
                          fontSize: '0.65rem', fontWeight: 700,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          px: 0.5, flexShrink: 0,
                        }}>
                          {compareCount}
                        </Box>
                      )}
                    </Box>
                  )}
                </Box>
              )}
            </NavLink>
          )

          return collapsed ? (
            <Tooltip key={item.path} title={item.label} placement="right">
              <Box>{navContent}</Box>
            </Tooltip>
          ) : (
            <Box key={item.path}>{navContent}</Box>
          )
        })}
      </Box>

      {/* Bottom section */}
      <Box
        sx={{
          borderTop: `1px solid ${DIVIDER_COLOR}`,
          px: collapsed ? 0 : 1.5,
          py: 1,
          display: 'flex',
          alignItems: 'center',
          gap: 1,
          justifyContent: collapsed ? 'center' : 'space-between',
          flexShrink: 0,
        }}
      >
        {!collapsed && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 0 }}>
            <Avatar
              sx={{
                width: 32,
                height: 32,
                fontSize: '0.75rem',
                bgcolor: '#b8975a',
                flexShrink: 0,
              }}
            >
              {getUserInitials(userName)}
            </Avatar>
            <Box sx={{ minWidth: 0 }}>
              <Typography
                variant="body2"
                sx={{
                  color: TEXT_WHITE,
                  fontWeight: 500,
                  fontSize: '0.8125rem',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {userName}
              </Typography>
              <Typography
                variant="caption"
                sx={{
                  color: '#64748b',
                  fontSize: '0.7rem',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  display: 'block',
                }}
              >
                {orgName}
              </Typography>
            </Box>
          </Box>
        )}

        <IconButton
          onClick={onToggle}
          size="small"
          sx={{ color: '#64748b', flexShrink: 0 }}
        >
          {collapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
        </IconButton>
      </Box>
    </Box>
  )
}
