import React, { useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import {
  AppBar,
  Box,
  CssBaseline,
  Divider,
  Drawer,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Toolbar,
  Typography,
  Collapse,
} from '@mui/material';
import {
  Menu as MenuIcon,
  Home as HomeIcon,
  Event as EventIcon,
  CalendarMonth as CalendarIcon,
  People as PeopleIcon,
  LocationOn as LocationIcon,
  Inventory as InventoryIcon,
  Person as PersonIcon,
  ExpandLess,
  ExpandMore,
  Assessment as ReportIcon,
  Kitchen as KitchenIcon,
  TableChart as TableIcon,
  Settings as SettingsIcon,
} from '@mui/icons-material';

const drawerWidth = 260;

interface NavItem {
  text: string;
  icon: React.ReactNode;
  path?: string;
  children?: NavItem[];
}

const navItems: NavItem[] = [
  { text: 'Home', icon: <HomeIcon />, path: '/' },
  { text: 'Calendario', icon: <CalendarIcon />, path: '/calendario' },
  {
    text: 'Eventi',
    icon: <EventIcon />,
    children: [
      { text: 'Lista Eventi', icon: <EventIcon />, path: '/eventi' },
      { text: 'Nuovo Evento', icon: <EventIcon />, path: '/eventi/nuovo' },
    ],
  },
  {
    text: 'Anagrafiche',
    icon: <PeopleIcon />,
    children: [
      { text: 'Clienti', icon: <PeopleIcon />, path: '/clienti' },
      { text: 'Location', icon: <LocationIcon />, path: '/location' },
      { text: 'Articoli', icon: <InventoryIcon />, path: '/articoli' },
      { text: 'Risorse', icon: <PersonIcon />, path: '/risorse' },
    ],
  },
  {
    text: 'Report',
    icon: <ReportIcon />,
    children: [
      { text: 'Riepilogo Cucina', icon: <KitchenIcon />, path: '/report/cucina' },
      { text: 'Riepilogo Allestimenti', icon: <TableIcon />, path: '/report/allestimenti' },
      { text: 'Griglia', icon: <TableIcon />, path: '/report/griglia' },
      { text: 'Impegni Articoli', icon: <InventoryIcon />, path: '/report/impegni' },
    ],
  },
  {
    text: 'Amministrazione',
    icon: <SettingsIcon />,
    children: [
      { text: 'Tipi Evento', icon: <SettingsIcon />, path: '/admin/tipi-evento' },
      { text: 'Categorie', icon: <SettingsIcon />, path: '/admin/categorie' },
      { text: 'Tipi Materiale', icon: <SettingsIcon />, path: '/admin/tipi-materiale' },
    ],
  },
];

const Layout: React.FC = () => {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({
    Eventi: true,
    Anagrafiche: false,
    Report: false,
    Amministrazione: false,
  });
  const navigate = useNavigate();
  const location = useLocation();

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  const handleMenuClick = (text: string) => {
    setOpenMenus((prev) => ({ ...prev, [text]: !prev[text] }));
  };

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

  const isActive = (path: string) => location.pathname === path;

  const renderNavItem = (item: NavItem, depth = 0) => {
    if (item.children) {
      return (
        <React.Fragment key={item.text}>
          <ListItemButton onClick={() => handleMenuClick(item.text)} sx={{ pl: 2 + depth * 2 }}>
            <ListItemIcon sx={{ minWidth: 40 }}>{item.icon}</ListItemIcon>
            <ListItemText primary={item.text} />
            {openMenus[item.text] ? <ExpandLess /> : <ExpandMore />}
          </ListItemButton>
          <Collapse in={openMenus[item.text]} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              {item.children.map((child) => renderNavItem(child, depth + 1))}
            </List>
          </Collapse>
        </React.Fragment>
      );
    }

    return (
      <ListItem key={item.text} disablePadding>
        <ListItemButton
          onClick={() => item.path && handleNavigation(item.path)}
          selected={item.path ? isActive(item.path) : false}
          sx={{
            pl: 2 + depth * 2,
            '&.Mui-selected': {
              backgroundColor: 'primary.light',
              '&:hover': {
                backgroundColor: 'primary.light',
              },
            },
          }}
        >
          <ListItemIcon sx={{ minWidth: 40 }}>{item.icon}</ListItemIcon>
          <ListItemText primary={item.text} />
        </ListItemButton>
      </ListItem>
    );
  };

  const drawer = (
    <div>
      <Toolbar
        sx={{
          backgroundColor: 'primary.main',
          color: 'white',
        }}
      >
        <Typography variant="h6" noWrap component="div" sx={{ fontWeight: 'bold' }}>
          Apollinare
        </Typography>
      </Toolbar>
      <Divider />
      <List>{navItems.map((item) => renderNavItem(item))}</List>
    </div>
  );

  return (
    <Box sx={{ display: 'flex' }}>
      <CssBaseline />
      <AppBar
        position="fixed"
        sx={{
          width: { sm: `calc(100% - ${drawerWidth}px)` },
          ml: { sm: `${drawerWidth}px` },
          backgroundColor: '#1976d2',
        }}
      >
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            edge="start"
            onClick={handleDrawerToggle}
            sx={{ mr: 2, display: { sm: 'none' } }}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap component="div">
            Apollinare - Catering & Banqueting
          </Typography>
        </Toolbar>
      </AppBar>
      <Box component="nav" sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}>
        <Drawer
          variant="temporary"
          open={mobileOpen}
          onClose={handleDrawerToggle}
          ModalProps={{
            keepMounted: true,
          }}
          sx={{
            display: { xs: 'block', sm: 'none' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
        >
          {drawer}
        </Drawer>
        <Drawer
          variant="permanent"
          sx={{
            display: { xs: 'none', sm: 'block' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
          open
        >
          {drawer}
        </Drawer>
      </Box>
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          p: 3,
          width: { sm: `calc(100% - ${drawerWidth}px)` },
          mt: '64px',
          backgroundColor: '#f5f5f5',
          minHeight: 'calc(100vh - 64px)',
        }}
      >
        <Outlet />
      </Box>
    </Box>
  );
};

export default Layout;
