import React, { useEffect, useMemo, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import {
  Box,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Tooltip,
  Snackbar,
  Alert,
} from "@mui/material";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useSidebar } from "../../components/sidebarContext";
import ConfirmDialog from "../../components/ConfirmDialog";
import GroupsIcon from "@mui/icons-material/Groups";
import CloseIcon from "@mui/icons-material/Close";
import {
  Dashboard as DashboardIcon,
  Logout as LogoutIcon,
  Person as PersonOutlineIcon,
} from "@mui/icons-material";
import InsertChartOutlinedIcon from "@mui/icons-material/InsertChartOutlined";
import { useSession } from "../../context/sessioncontext";

type MenuSubItem = {
  text: string;
  icon: React.ReactElement;
  path: string;
};

type MenuItem = {
  text: string;
  icon: React.ReactElement;
  path?: string;
  subItems?: MenuSubItem[];
};

const ITEM_MIN_HEIGHT = 44; 
const LEFT_BAR_WIDTH = 3;

const mainItemSx = (isSelected: boolean, isMobile: boolean) => ({
  my: 0.5,
  mx: 0.5,
  borderRadius: 1.5,
  px: !isMobile ? 1.5 : 0,
  py: 1,
  minHeight: ITEM_MIN_HEIGHT,
  alignItems: "center",
  boxSizing: "border-box",
  border: isSelected
    ? "1px solid rgba(255,255,255,0.25)"  
    : "1px solid transparent",
  transition:
    "background 0.2s, backdrop-filter 0.2s, transform 0.2s, border-color 0.2s, color 0.2s",
  bgcolor: isSelected ? "rgba(255,255,255,0.12)" : "transparent",
  backdropFilter: isSelected ? "blur(8px)" : "none",
  color: "#FFFFFF",
  position: "relative",

  "&::before": {
    content: '""',
    position: "absolute",
    left: 0,
    top: 6,
    height: "70%",
    width: LEFT_BAR_WIDTH,
    backgroundColor: isSelected ? "#FFFFFF" : "transparent",
    transition: "background-color 0.2s, opacity 0.2s",
  },

  "&:hover": {
    bgcolor: "rgba(255,255,255,0.18)",
    backdropFilter: "blur(8px)",
    transform: "scale(1.02)",
    borderColor: "rgba(255,255,255,0.25)",  
    "&::before": { backgroundColor: "#FFFFFF" },
  },
});



const subItemSx = (isSelected: boolean) => ({
  my: 0.5,
  borderRadius: 1.25,
  px: 1.5,
  py: 0.5,
  minHeight: ITEM_MIN_HEIGHT - 6,
  alignItems: "center",
  boxSizing: "border-box",
  border: isSelected
    ? "1px solid rgba(255,255,255,0.25)"
    : "1px solid transparent",
  transition:
    "background 0.2s, backdrop-filter 0.2s, transform 0.2s, border-color 0.2s, color 0.2s",
  bgcolor: isSelected ? "rgba(255,255,255,0.12)" : "transparent",
  backdropFilter: isSelected ? "blur(8px)" : "none",
  color: "#FFFFFF",
  position: "relative",

  "&::before": {
    content: '""',
    position: "absolute",
    left: 0,
    top: 0,
    height: "100%",
    width: LEFT_BAR_WIDTH,
    backgroundColor: isSelected ? "#1976D2" : "transparent",
    transition: "background-color 0.2s, opacity 0.2s",
  },

  "&:hover": {
    bgcolor: "rgba(255,255,255,0.18)",
    backdropFilter: "blur(8px)",
    transform: "scale(1.02)",
    borderColor: "rgba(255,255,255,0.25)",
    "&::before": { backgroundColor: "#1976D2" },
  },
});


const iconBoxSx = (hasLabel: boolean) => ({
  color: "#FFFFFF",
  minWidth: 36,
  mr: hasLabel ? 1.5 : 0,
  justifyContent: "center",
  display: "flex",
  alignItems: "center",
  height: 24,
});

const textProps = (isSelected: boolean) => ({
  fontSize: 14,
  lineHeight: 1.25,
  fontWeight: isSelected ? 600 : 500,
  color: "#FFFFFF",
  ml: 0.5,
});

const Sidebar: React.FC = () => {
  const { isOpen, toggleSidebar } = useSidebar();
  const theme = useTheme();
  const { logout } = useSession();
  const navigate = useNavigate();
  const location = useLocation();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [dialogOpen, setDialogOpen] = useState(false);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [membershipOpen, setMembershipOpen] = useState(false);
  const [userType, setUserType] = useState<string | null>(null);

  // Read user type once
  useEffect(() => {
    const storedUserData = localStorage.getItem("user");
    if (storedUserData) {
      try {
        const storedUser = JSON.parse(storedUserData);
        setUserType(storedUser?.userType ?? null);
      } catch (e) {
        console.error("Failed to parse user data from localStorage:", e);
      }
    }
  }, []);

  // Persist sidebar state
  useEffect(() => {
    localStorage.setItem("sidebarIsOpen", isOpen.toString());
  }, [isOpen]);

  const baseItems = useMemo<MenuItem[]>(() => {
    const items: MenuItem[] = [
      { text: "Dashboard", icon: <DashboardIcon />, path: "/dashboard" },
      { text: "Markets", icon: <InsertChartOutlinedIcon />, path: "/markets" },
      { text: "Profile", icon: <PersonOutlineIcon />, path: "/profile" },
    ];
    if (userType === "ADMIN" || userType === "SUPERADMIN") {
      items.push({ text: "Users", icon: <GroupsIcon />, path: "/users" });
    }
    return items;
  }, [userType]);

  const menuItems: { items: MenuItem[] }[] = useMemo(
    () => [{ items: baseItems }],
    [baseItems]
  );

  const isItemSelected = (path?: string) =>
    !!path &&
    (location.pathname === path ||
      location.pathname.startsWith(path + "/"));

  const handleLogout = () => setDialogOpen(true);

  const handleLogoutConfirm = () => {
    for (const k of ["token", "user"]) {
      sessionStorage.removeItem(k);
      localStorage.removeItem(k);
    }
    setSnackbarOpen(true);
    logout();
    navigate("/", { replace: true });
    setDialogOpen(false);
    if (isMobile) toggleSidebar();
  };

  const handleDialogClose = () => setDialogOpen(false);
  const handleSnackbarClose = () => setSnackbarOpen(false);
  const handleMembershipToggle = () => setMembershipOpen((prev) => !prev);

  const withMaybeTooltip = (label: string, child: React.ReactNode) =>
    isOpen && !isMobile ? (
      <>{child}</>
    ) : (
      <Tooltip title={label} placement="right">
        <span>{child}</span>
      </Tooltip>
    );

  return (
    <>
      {isMobile && isOpen && (
        <Box
          onClick={toggleSidebar}
          sx={{
            position: "fixed",
            top: 0,
            left: "80%",
            width: "20%",
            height: "100vh",
            backgroundColor: "rgba(0,0,0,0.3)",
            zIndex: 1299,
          }}
        />
      )}

      <Box
        role="navigation"
        aria-label="Primary"
        sx={{
          display: "flex",
          flexDirection: "column",
          width: {
            xs: isOpen ? "80%" : "0",
            sm: isOpen ? "230px" : "90px",
          },
          bgcolor: "#0D1629",
          color: "#FFFFFF",
          height: "100vh",
          transition: "width 0.3s ease-in-out",
          borderRight: "1px solid #E0E0E0",
          zIndex: 1300,
          position: "fixed",
          top: 0,
          left: 0,
          pt: 1,
          overflowX: "hidden",
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            py: 1,
            minHeight: "56px",
            width: "100%",
          }}
        />
        {(!isMobile || (isMobile && isOpen)) && (
          <>
            {menuItems.map((section, idx) => (
              <Box key={idx} sx={{ px: 1, flexGrow: 1 }}>
                <List disablePadding>
                  {section.items.map((item) => {
                    const selected = isItemSelected(item.path);
                    const button = (
                      <ListItemButton
                        onClick={() => {
                          if (item.subItems) {
                            handleMembershipToggle();
                          } else if (item.path) {
                            navigate(item.path);
                            if (isMobile) toggleSidebar();
                          }
                        }}
                        selected={selected}
                        sx={mainItemSx(selected, isMobile)}
                        aria-current={selected ? "page" : undefined}
                        aria-label={!isOpen ? item.text : undefined}
                      >
                        <ListItemIcon sx={iconBoxSx(isOpen)}>
                          {item.icon}
                        </ListItemIcon>
                        {isOpen && (
                          <ListItemText
                            primary={item.text}
                            primaryTypographyProps={textProps(selected)}
                            sx={{
                              whiteSpace: "nowrap",
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                            }}
                          />
                        )}
                      </ListItemButton>
                    );

                    return (
                      <Box key={item.text}>
                        {withMaybeTooltip(item.text, button)}

                        {item.subItems && isOpen && membershipOpen && (
                          <List sx={{ pl: 4 }}>
                            {item.subItems.map((subItem) => {
                              const subSelected = isItemSelected(subItem.path);
                              const subBtn = (
                                <ListItemButton
                                  onClick={() => {
                                    navigate(subItem.path);
                                    if (isMobile) toggleSidebar();
                                  }}
                                  selected={subSelected}
                                  sx={subItemSx(subSelected)}
                                  aria-current={subSelected ? "page" : undefined}
                                  aria-label={!isOpen ? subItem.text : undefined}
                                >
                                  <ListItemIcon
                                    sx={{
                                      ...iconBoxSx(true),
                                      color: subSelected ? "#1976D2" : "#FFFFFF",
                                    }}
                                  >
                                    {subItem.icon}
                                  </ListItemIcon>
                                  <ListItemText
                                    primary={subItem.text}
                                    primaryTypographyProps={{
                                      ...textProps(subSelected),
                                      color: subSelected ? "#1976D2" : "#FFFFFF",
                                      fontSize: 13,
                                    }}
                                  />
                                </ListItemButton>
                              );

                              return (
                                <Tooltip
                                  key={subItem.path}
                                  title={isOpen && !isMobile ? "" : subItem.text}
                                  placement="right"
                                >
                                  <span>{subBtn}</span>
                                </Tooltip>
                              );
                            })}
                          </List>
                        )}
                      </Box>
                    );
                  })}
                </List>
              </Box>
            ))}
            <Box sx={{ px: 1, mt: "auto", pb: 2 }}>
              {withMaybeTooltip(
                "Logout",
                <ListItemButton
                  onClick={handleLogout}
                  sx={{
                    my: 0.5,
                    mx: 0.5,
                    borderRadius: 1.5,
                    px: 1.5,
                    py: 1,
                    minHeight: ITEM_MIN_HEIGHT,
                    alignItems: "center",
                    boxSizing: "border-box",
                    border: "1px solid transparent",
                    transition:
                      "background 0.2s, backdrop-filter 0.2s, transform 0.2s, border-color 0.2s",
                    bgcolor: "transparent",
                    color: "#FF4444",
                    position: "relative",
                    "&::before": {
                      content: '""',
                      position: "absolute",
                      left: 0,
                      top: 0,
                      height: "100%",
                      width: LEFT_BAR_WIDTH,
                      backgroundColor: "transparent",
                      transition: "background-color 0.2s",
                    },
                    "&:hover": {
                      bgcolor: "rgba(255,68,68,0.25)",
                      backdropFilter: "blur(8px)",
                      borderColor: "rgba(255,68,68,0.2)",
                      transform: "scale(1.02)",
                      "&::before": {
                        backgroundColor: "#FF4444",
                      },
                    },
                  }}
                >
                  <ListItemIcon
                    sx={{
                      ...iconBoxSx(isOpen),
                      color: "#FF4444",
                    }}
                  >
                    <LogoutIcon />
                  </ListItemIcon>
                  {isOpen && (
                    <ListItemText
                      primary="Logout"
                      primaryTypographyProps={{
                        fontSize: 14,
                        lineHeight: 1.25,
                        fontWeight: 500,
                        color: "#FF4444",
                        ml: 0.5,
                      }}
                    />
                  )}
                </ListItemButton>
              )}
            </Box>
          </>
        )}
      </Box>

      <ConfirmDialog
        open={dialogOpen}
        title="Log out confirmation"
        message="Are you sure you want to log out?"
        onConfirm={handleLogoutConfirm}
        onClose={handleDialogClose}
        confirmText="Logout"
        cancelText="Cancel"
      />
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity="success"
          sx={{ width: isMobile ? "90%" : "100%" }}
          action={
            <IconButton
              size="small"
              aria-label="close"
              color="inherit"
              onClick={handleSnackbarClose}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          }
        >
          Logged out successfully
        </Alert>
      </Snackbar>
    </>
  );
};

export default Sidebar;
