import { useMemo } from 'react';
import {
  Box,
  Drawer,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Toolbar,
  Tooltip,
} from '@mui/material';
import {
  Dashboard as DashboardIcon,
  DirectionsCar,
  Build,
  People,
  Air,
  CalendarMonth,
  MenuBook,
  AdminPanelSettings,
  Settings,
  Menu as MenuIcon,
  LocalShipping,
  BugReport,
  BookOnline,
  Forum,
  AssignmentTurnedIn,
  AccountBalance as AccountBalanceIcon,
  Checkroom as CheckroomIcon,
  Schedule,
} from '@mui/icons-material';
import { useNavigate, useLocation } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useLayout, DRAWER_WIDTH, DRAWER_WIDTH_COLLAPSED } from '../../contexts/LayoutContext';
import { usePermissionContext } from '../../contexts/PermissionContext';
import { preferencesApi } from '../../services/settings';

export { DRAWER_WIDTH, DRAWER_WIDTH_COLLAPSED };

interface NavigationItem {
  text: string;
  icon: JSX.Element;
  path: string;
  permission?: string;
}

const baseNavigationItems: NavigationItem[] = [
  {
    text: 'Dashboard',
    icon: <DashboardIcon />,
    path: '/dashboard',
  },
  {
    text: 'Chat',
    icon: <Forum />,
    path: '/chat',
  },
  {
    text: 'Kalender',
    icon: <CalendarMonth />,
    path: '/kalender',
    permission: 'kalender:view',
  },
  {
    text: 'Fahrzeugbuchungen',
    icon: <BookOnline />,
    path: '/fahrzeugbuchungen',
    permission: 'fahrzeugbuchungen:view',
  },
  {
    text: 'Fahrzeuge',
    icon: <DirectionsCar />,
    path: '/fahrzeuge',
    permission: 'fahrzeuge:view',
  },
  {
    text: 'Ausrüstung',
    icon: <Build />,
    path: '/ausruestung',
    permission: 'ausruestung:view',
  },
  {
    text: 'Pers. Ausrüstung',
    icon: <CheckroomIcon />,
    path: '/persoenliche-ausruestung',
    permission: 'persoenliche_ausruestung:view',
  },
  {
    text: 'Mitglieder',
    icon: <People />,
    path: '/mitglieder',
    permission: 'mitglieder:view_own',
  },
  {
    text: 'Atemschutz',
    icon: <Air />,
    path: '/atemschutz',
    permission: 'atemschutz:view',
  },
  {
    text: 'Wissen',
    icon: <MenuBook />,
    path: '/wissen',
    permission: 'wissen:view',
  },
  {
    text: 'Bestellungen',
    icon: <LocalShipping />,
    path: '/bestellungen',
    permission: 'bestellungen:view',
  },
  {
    text: 'Interne Bestellungen',
    icon: <Build />,
    path: '/ausruestungsanfrage',
    permission: 'ausruestungsanfrage:view',
  },
  {
    text: 'Checklisten',
    icon: <AssignmentTurnedIn />,
    path: '/checklisten',
    permission: 'checklisten:view',
  },
  {
    text: 'Buchhaltung',
    icon: <AccountBalanceIcon />,
    path: '/buchhaltung',
    permission: 'buchhaltung:view',
  },
  {
    text: 'Issues',
    icon: <BugReport />,
    path: '/issues',
    permission: 'issues:view_own',
  },
  {
    text: 'Geplante Nachrichten',
    icon: <Schedule />,
    path: '/geplante-nachrichten',
    permission: 'scheduled_messages:view',
  },
];

const adminItem: NavigationItem = {
  text: 'Admin',
  icon: <AdminPanelSettings />,
  path: '/admin',
};

const adminSettingsItem: NavigationItem = {
  text: 'Einstellungen',
  icon: <Settings />,
  path: '/admin/settings',
};

interface SidebarProps {
  mobileOpen: boolean;
  onMobileClose: () => void;
}

function Sidebar({ mobileOpen, onMobileClose }: SidebarProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { sidebarCollapsed, toggleSidebar } = useLayout();
  const { hasPermission } = usePermissionContext();

  const { data: preferences } = useQuery({
    queryKey: ['user-preferences'],
    queryFn: preferencesApi.get,
    staleTime: 5 * 60 * 1000,
  });

  const menuOrder: string[] = (preferences?.menuOrder as string[] | undefined) ?? [];

  const navigationItems = useMemo((): NavigationItem[] => {
    const items = baseNavigationItems
      .map((item) => {
        // Ausrüstungsanfrage is visible if user has any of the three relevant permissions
        if (item.path === '/ausruestungsanfrage') {
          const canSee =
            hasPermission('ausruestungsanfrage:view') ||
            hasPermission('ausruestungsanfrage:create_request') ||
            hasPermission('ausruestungsanfrage:approve');
          return { ...item, permission: canSee ? undefined : 'ausruestungsanfrage:view' };
        }
        return item;
      })
      .filter((item) => !item.permission || hasPermission(item.permission));

    // Apply custom menu order
    if (menuOrder.length > 0) {
      items.sort((a, b) => {
        const aIdx = menuOrder.indexOf(a.path);
        const bIdx = menuOrder.indexOf(b.path);
        if (aIdx !== -1 && bIdx !== -1) return aIdx - bIdx;
        if (aIdx !== -1) return -1;
        if (bIdx !== -1) return 1;
        return 0;
      });
    }

    return hasPermission('admin:view') ? [...items, adminItem, adminSettingsItem] : items;
  }, [hasPermission, menuOrder]);

  const handleNavigation = (path: string) => {
    navigate(path);
    onMobileClose();
  };

  const drawerContent = (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <Toolbar />
      <Box sx={{ display: 'flex', justifyContent: sidebarCollapsed ? 'center' : 'flex-end', px: 1, py: 0.5 }}>
        <IconButton onClick={toggleSidebar} aria-label="Sidebar umschalten">
          <MenuIcon />
        </IconButton>
      </Box>
      <List sx={{ flex: 1 }}>
        {navigationItems.map((item) => {
          const isActive = location.pathname === item.path;
          return (
            <ListItem key={item.text} disablePadding>
              <Tooltip
                title={item.text}
                placement="right"
                arrow
                disableHoverListener={!sidebarCollapsed}
              >
                <ListItemButton
                  selected={isActive}
                  onClick={() => handleNavigation(item.path)}
                  aria-label={`Zu ${item.text} navigieren`}
                  sx={{
                    justifyContent: sidebarCollapsed ? 'center' : 'initial',
                    '&.Mui-selected': {
                      backgroundColor: 'primary.light',
                      color: 'primary.contrastText',
                      '&:hover': {
                        backgroundColor: 'primary.main',
                      },
                      '& .MuiListItemIcon-root': {
                        color: 'primary.contrastText',
                      },
                    },
                  }}
                >
                  <ListItemIcon
                    sx={{
                      color: isActive ? 'inherit' : 'text.secondary',
                      minWidth: sidebarCollapsed ? 0 : undefined,
                      justifyContent: 'center',
                    }}
                  >
                    {item.icon}
                  </ListItemIcon>
                  <ListItemText
                    primary={item.text}
                    sx={{
                      display: sidebarCollapsed ? 'none' : 'block',
                    }}
                  />
                </ListItemButton>
              </Tooltip>
            </ListItem>
          );
        })}
      </List>
    </Box>
  );

  return (
    <>
      {/* Mobile drawer */}
      <Drawer
        variant="temporary"
        open={mobileOpen}
        onClose={onMobileClose}
        ModalProps={{
          keepMounted: true, // Better mobile performance
        }}
        sx={{
          display: { xs: 'block', sm: 'none' },
          '& .MuiDrawer-paper': {
            boxSizing: 'border-box',
            width: DRAWER_WIDTH,
          },
        }}
        aria-label="Mobile Navigation"
      >
        {drawerContent}
      </Drawer>

      {/* Desktop drawer */}
      <Drawer
        variant="permanent"
        sx={{
          display: { xs: 'none', sm: 'block' },
          width: sidebarCollapsed ? DRAWER_WIDTH_COLLAPSED : DRAWER_WIDTH,
          flexShrink: 0,
          '& .MuiDrawer-paper': {
            width: sidebarCollapsed ? DRAWER_WIDTH_COLLAPSED : DRAWER_WIDTH,
            boxSizing: 'border-box',
            transition: 'width 225ms cubic-bezier(0.4, 0, 0.6, 1)',
            overflowX: 'hidden',
          },
        }}
        open
        aria-label="Desktop Navigation"
      >
        {drawerContent}
      </Drawer>
    </>
  );
}

export default Sidebar;
