import { useState, useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { Box, Tabs, Tab, Paper, Typography, Breadcrumbs, Link } from "@mui/material";
import {
  Dashboard as DashboardIcon,
  Inventory as ArticleIcon,
  Place as LocationIcon,
  SwapHoriz as MovementIcon,
  Assessment as StockIcon,
  FactCheck as InventoryIcon,
} from "@mui/icons-material";

const navItems = [
  { label: "Dashboard", path: "/warehouse", icon: <DashboardIcon fontSize="small" /> },
  { label: "Articoli", path: "/warehouse/articles", icon: <ArticleIcon fontSize="small" /> },
  { label: "Magazzini", path: "/warehouse/locations", icon: <LocationIcon fontSize="small" /> },
  { label: "Movimenti", path: "/warehouse/movements", icon: <MovementIcon fontSize="small" /> },
  { label: "Giacenze", path: "/warehouse/stock", icon: <StockIcon fontSize="small" /> },
  { label: "Inventario", path: "/warehouse/inventory", icon: <InventoryIcon fontSize="small" /> },
];

export default function WarehouseLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const [value, setValue] = useState(0);

  useEffect(() => {
    // Find the matching tab based on current path
    const index = navItems.findIndex((item) => {
      if (item.path === "/warehouse") {
        return location.pathname === "/warehouse";
      }
      return location.pathname.startsWith(item.path);
    });

    if (index !== -1) {
      setValue(index);
    } else {
      // If no match (e.g. sub-pages), keep the closest parent or default
      // Logic could be improved here but keeping it simple for now
      if (location.pathname.includes("articles")) setValue(1);
      else if (location.pathname.includes("locations")) setValue(2);
      else if (location.pathname.includes("movements")) setValue(3);
      else if (location.pathname.includes("stock")) setValue(4);
      else if (location.pathname.includes("inventory")) setValue(5);
      else setValue(0);
    }
  }, [location.pathname]);

  const handleChange = (_event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
    navigate(navItems[newValue].path);
  };

  return (
    <Box sx={{ display: "flex", flexDirection: "column", height: "100%", gap: 2 }}>
      {/* Header & Navigation */}
      <Paper sx={{ px: 2, pt: 2, pb: 0 }}>
        <Box sx={{ mb: 2 }}>
          <Typography variant="h5" component="h1" fontWeight="bold" gutterBottom>
            Gestione Magazzino
          </Typography>
          <Breadcrumbs aria-label="breadcrumb">
            <Link underline="hover" color="inherit" href="/">
              Home
            </Link>
            <Typography color="text.primary">Magazzino</Typography>
            {navItems[value]?.label !== "Dashboard" && (
              <Typography color="text.primary">{navItems[value]?.label}</Typography>
            )}
          </Breadcrumbs>
        </Box>

        <Tabs
          value={value}
          onChange={handleChange}
          variant="scrollable"
          scrollButtons="auto"
          aria-label="warehouse navigation tabs"
          sx={{ borderBottom: 1, borderColor: "divider" }}
        >
          {navItems.map((item, index) => (
            <Tab
              key={item.path}
              label={item.label}
              icon={item.icon}
              iconPosition="start"
              id={`warehouse-tab-${index}`}
              aria-controls={`warehouse-tabpanel-${index}`}
            />
          ))}
        </Tabs>
      </Paper>

      {/* Content Area */}
      <Box sx={{ flex: 1, minHeight: 0, overflow: "auto" }}>
        <Outlet />
      </Box>
    </Box>
  );
}
