import { useState } from "react";
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import {
  Box,
  Drawer,
  AppBar,
  Toolbar,
  List,
  Typography,
  Divider,
  IconButton,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  Menu as MenuIcon,
  Dashboard as DashboardIcon,
  Event as EventIcon,
  People as PeopleIcon,
  Place as PlaceIcon,
  Inventory as InventoryIcon,
  Person as PersonIcon,
  CalendarMonth as CalendarIcon,
  Print as PrintIcon,
  Close as CloseIcon,
  Extension as ModulesIcon,
} from "@mui/icons-material";
import CollaborationIndicator from "./collaboration/CollaborationIndicator";

const DRAWER_WIDTH = 240;
const DRAWER_WIDTH_COLLAPSED = 64;

const menuItems = [
  { text: "Dashboard", icon: <DashboardIcon />, path: "/" },
  { text: "Calendario", icon: <CalendarIcon />, path: "/calendario" },
  { text: "Eventi", icon: <EventIcon />, path: "/eventi" },
  { text: "Clienti", icon: <PeopleIcon />, path: "/clienti" },
  { text: "Location", icon: <PlaceIcon />, path: "/location" },
  { text: "Articoli", icon: <InventoryIcon />, path: "/articoli" },
  { text: "Risorse", icon: <PersonIcon />, path: "/risorse" },
  { text: "Report", icon: <PrintIcon />, path: "/report-templates" },
  { text: "Moduli", icon: <ModulesIcon />, path: "/modules" },
];

export default function Layout() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const theme = useTheme();

  // Breakpoints
  const isMobile = useMediaQuery(theme.breakpoints.down("sm")); // < 600px
  const isTablet = useMediaQuery(theme.breakpoints.between("sm", "md")); // 600-900px

  // Drawer width based on screen size
  const drawerWidth = isTablet ? DRAWER_WIDTH_COLLAPSED : DRAWER_WIDTH;

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

  const drawer = (
    <Box sx={{ height: "100%", display: "flex", flexDirection: "column" }}>
      <Toolbar
        sx={{
          justifyContent: isTablet ? "center" : "space-between",
          minHeight: { xs: 56, sm: 64 },
        }}
      >
        {!isTablet && (
          <Typography
            variant="h6"
            noWrap
            component="div"
            sx={{ fontWeight: "bold" }}
          >
            Apollinare
          </Typography>
        )}
        {isMobile && (
          <IconButton onClick={handleDrawerToggle} sx={{ ml: "auto" }}>
            <CloseIcon />
          </IconButton>
        )}
      </Toolbar>
      <Divider />
      <List sx={{ flex: 1, py: 1 }}>
        {menuItems.map((item) => (
          <ListItem key={item.text} disablePadding sx={{ px: 1 }}>
            <ListItemButton
              selected={location.pathname === item.path}
              onClick={() => {
                navigate(item.path);
                if (isMobile) setMobileOpen(false);
              }}
              sx={{
                borderRadius: 1,
                minHeight: 48,
                justifyContent: isTablet ? "center" : "flex-start",
                px: isTablet ? 1 : 2,
              }}
            >
              <ListItemIcon
                sx={{
                  minWidth: isTablet ? 0 : 40,
                  justifyContent: "center",
                }}
              >
                {item.icon}
              </ListItemIcon>
              {!isTablet && <ListItemText primary={item.text} />}
            </ListItemButton>
          </ListItem>
        ))}
      </List>
      {!isTablet && (
        <Box sx={{ p: 2, borderTop: 1, borderColor: "divider" }}>
          <Typography variant="caption" color="text.secondary">
            © 2025 Apollinare
          </Typography>
        </Box>
      )}
    </Box>
  );

  return (
    <Box sx={{ display: "flex", minHeight: "100vh" }}>
      <AppBar
        position="fixed"
        sx={{
          width: {
            xs: "100%",
            sm: `calc(100% - ${drawerWidth}px)`,
          },
          ml: { sm: `${drawerWidth}px` },
          boxShadow: 1,
        }}
      >
        <Toolbar sx={{ minHeight: { xs: 56, sm: 64 } }}>
          <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"
            sx={{
              fontSize: { xs: "1rem", sm: "1.25rem" },
              flexGrow: 1,
            }}
          >
            {isMobile ? "Apollinare" : "Catering & Banqueting Management"}
          </Typography>

          {/* Collaboration Indicator */}
          <CollaborationIndicator compact={isMobile} />
        </Toolbar>
      </AppBar>

      {/* Mobile Drawer */}
      <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: DRAWER_WIDTH,
            },
          }}
        >
          {drawer}
        </Drawer>

        {/* Desktop/Tablet Drawer */}
        <Drawer
          variant="permanent"
          sx={{
            display: { xs: "none", sm: "block" },
            "& .MuiDrawer-paper": {
              boxSizing: "border-box",
              width: drawerWidth,
              transition: theme.transitions.create("width", {
                easing: theme.transitions.easing.sharp,
                duration: theme.transitions.duration.enteringScreen,
              }),
            },
          }}
          open
        >
          {drawer}
        </Drawer>
      </Box>

      {/* Main Content */}
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          width: {
            xs: "100vw",
            sm: `calc(100vw - ${drawerWidth}px)`,
          },
          height: "100vh",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {/* Toolbar spacer */}
        <Toolbar sx={{ minHeight: { xs: 56, sm: 64 }, flexShrink: 0 }} />

        {/* Content */}
        <Box
          sx={{
            flex: 1,
            display: "flex",
            flexDirection: "column",
            minHeight: 0, // Important: allows flex children to shrink below content size
            p: location.pathname.startsWith("/report-editor")
              ? 0
              : { xs: 1.5, sm: 2, md: 3 },
            overflow: location.pathname.startsWith("/report-editor")
              ? "hidden"
              : "auto",
          }}
        >
          <Outlet />
        </Box>
      </Box>
    </Box>
  );
}
