import ApartmentOutlined from "@mui/icons-material/ApartmentOutlined";
import BadgeOutlined from "@mui/icons-material/BadgeOutlined";
import GridViewOutlined from "@mui/icons-material/GridViewOutlined";
import GroupsOutlined from "@mui/icons-material/GroupsOutlined";
import HomeOutlined from "@mui/icons-material/HomeOutlined";
import ImageOutlined from "@mui/icons-material/ImageOutlined";
import KeyOutlined from "@mui/icons-material/KeyOutlined";
import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";
import PeopleOutlineOutlined from "@mui/icons-material/PeopleOutlineOutlined";
import PersonOffOutlined from "@mui/icons-material/PersonOffOutlined";
import RedeemOutlined from "@mui/icons-material/RedeemOutlined";
import SecurityOutlined from "@mui/icons-material/SecurityOutlined";
import AppBar from "@mui/material/AppBar";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Divider from "@mui/material/Divider";
import Drawer from "@mui/material/Drawer";
import List from "@mui/material/List";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Stack from "@mui/material/Stack";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useMemo, useState } from "react";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { AppIdentity } from "@/shared/ui/AppIdentity.jsx";
import { useExternalAuth } from "../auth/ExternalAuthProvider.jsx";
import { hasAnyExternalCapability } from "../config/capabilities.js";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";
import { LanguageSwitcher } from "../i18n/LanguageSwitcher.jsx";
import { useExternalSessionBrand } from "../shared/useExternalSessionBrand.js";

const drawerWidth = 248;
const navigation = [
  { icon: HomeOutlined, labelKey: "nav.overview", path: "/overview" },
  { capabilities: ["user:list", "user:update", "user:ban", "user-level:grant"], icon: PeopleOutlineOutlined, labelKey: "nav.users", path: "/users" },
  { capabilities: ["user-ban:list", "user:unban"], icon: PersonOffOutlined, labelKey: "nav.bans", path: "/bans" },
  { capabilities: ["host:list"], icon: BadgeOutlined, labelKey: "nav.hosts", path: "/organization/hosts" },
  { capabilities: ["agency:list"], icon: ApartmentOutlined, labelKey: "nav.agencies", path: "/organization/agencies" },
  { capabilities: ["bd:list"], icon: GroupsOutlined, labelKey: "nav.bds", path: "/organization/bds" },
  { capabilities: ["bd-manager:list"], icon: SecurityOutlined, labelKey: "nav.bdManagers", path: "/organization/bd-leaders" },
  { capabilities: ["super-admin:list"], icon: SecurityOutlined, labelKey: "nav.superAdmins", path: "/organization/super-admins" },
  { capabilities: ["room:list", "room:update"], icon: MeetingRoomOutlined, labelKey: "nav.rooms", path: "/rooms" },
  { capabilities: ["privilege:list", "privilege:grant", "pretty-id:grant", "user-title:grant", "room-background:grant"], icon: RedeemOutlined, labelKey: "nav.grants", path: "/grants" },
  { capabilities: ["banner:create"], icon: ImageOutlined, labelKey: "nav.banners", path: "/banners" },
  { capabilities: ["team:view"], icon: GroupsOutlined, labelKey: "nav.team", path: "/organization/team" }
];

const isItemActive = (item, pathname) => pathname === item.path || pathname.startsWith(`${item.path}/`);

export function ExternalAdminLayout() {
  const theme = useTheme();
  const mobile = useMediaQuery(theme.breakpoints.down("md"));
  const [sheetOpen, setSheetOpen] = useState(false);
  const { logout, session } = useExternalAuth();
  const { t } = useExternalI18n();
  const location = useLocation();
  const navigate = useNavigate();
  const visibleNavigation = useMemo(
    () => navigation.filter((item) => !item.capabilities || hasAnyExternalCapability(session, item.capabilities)),
    [session]
  );
  const current = [...visibleNavigation].reverse().find((item) => isItemActive(item, location.pathname));
  // The H5 tab bar keeps three primary destinations reachable with a thumb; everything else lives in the "More" sheet.
  const tabs = visibleNavigation.slice(0, 3);
  const moreActive = !tabs.some((item) => isItemActive(item, location.pathname));
  useExternalSessionBrand(session, t("app.title"));

  const handleLogout = async () => {
    setSheetOpen(false);
    await logout();
    navigate("/login", { replace: true });
  };

  const accountCard = (
    <>
      <Avatar className="external-user-avatar">{String(session?.account || "A").slice(0, 1).toUpperCase()}</Avatar>
      <Box sx={{ minWidth: 0 }}>
        <Typography fontWeight={650} noWrap sx={{ lineHeight: 1.25 }}>{session?.account}</Typography>
        <Typography color="text.secondary" noWrap variant="caption">{session?.appName || session?.appCode}{session?.displayName ? ` · ${session.displayName}` : ""}</Typography>
      </Box>
    </>
  );

  const sidebar = (
    <Box className="external-sidebar" sx={{ width: drawerWidth }}>
      <Box className="external-logo">
        <AppIdentity
          appCode={session?.appCode}
          appName={session?.appName || session?.appCode}
          className="external-sidebar-brand"
          logoUrl={session?.logoUrl}
          showLogoFallback={false}
          size="large"
        />
      </Box>
      <Divider />
      <List className="external-nav">
        {visibleNavigation.map((item) => {
          const Icon = item.icon;
          return (
            <ListItemButton
              component={NavLink}
              key={item.path}
              selected={isItemActive(item, location.pathname)}
              to={item.path}
            >
              <ListItemIcon><Icon fontSize="small" /></ListItemIcon>
              <ListItemText primary={t(item.labelKey)} />
            </ListItemButton>
          );
        })}
      </List>
      <Box className="external-sidebar-footer">
        <Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>{accountCard}</Stack>
        <Button color="inherit" onClick={() => navigate("/change-password")} startIcon={<KeyOutlined />}>{t("auth.changePassword")}</Button>
        <Button onClick={handleLogout} startIcon={<LogoutOutlined />} variant="outlined">{t("auth.logout")}</Button>
      </Box>
    </Box>
  );

  return (
    <Box className="external-shell">
      {/* Physical margins/anchors are written for LTR; the RTL Emotion cache flips them for Arabic. */}
      <AppBar
        className="external-header"
        color="inherit"
        elevation={0}
        position="fixed"
        sx={{
          ml: { md: `${drawerWidth}px` },
          width: { md: `calc(100% - ${drawerWidth}px)` }
        }}
      >
        <Toolbar>
          {mobile ? (
            <AppIdentity
              appCode={session?.appCode}
              appName={session?.appName || session?.appCode}
              className="external-mobile-brand"
              logoUrl={session?.logoUrl}
              showLogoFallback={false}
              size="small"
            />
          ) : (
            <Typography className="external-header-title" component="h2" noWrap>{t(current?.labelKey || "app.shortTitle")}</Typography>
          )}
          <Box flex={1} />
          <Stack direction="row" spacing={1.5} sx={{ alignItems: "center" }}>
            <LanguageSwitcher compact={mobile} />
            {!mobile ? accountCard : null}
          </Stack>
        </Toolbar>
      </AppBar>
      <Drawer anchor="left" open variant="permanent" sx={{ display: { xs: "none", md: "block" }, "& .MuiDrawer-paper": { width: drawerWidth } }}>{sidebar}</Drawer>
      <Box className="external-main" component="main" sx={{ ml: { md: `${drawerWidth}px` } }}>
        <Toolbar className="external-toolbar-spacer" />
        <Outlet />
      </Box>
      {/* Shown below the md breakpoint via index.css; sx display rules would lose to the stylesheet cascade. */}
      <Box className="external-tabbar" component="nav">
        {tabs.map((item) => {
          const Icon = item.icon;
          return (
            <NavLink className={isItemActive(item, location.pathname) ? "external-tab is-active" : "external-tab"} key={item.path} to={item.path}>
              <Icon />
              <span className="external-tab-label">{t(item.labelKey)}</span>
            </NavLink>
          );
        })}
        <button aria-label={t("nav.more")} className={moreActive ? "external-tab is-active" : "external-tab"} type="button" onClick={() => setSheetOpen(true)}>
          <GridViewOutlined />
          <span className="external-tab-label">{t("nav.more")}</span>
        </button>
      </Box>
      <Drawer
        anchor="bottom"
        open={sheetOpen}
        slotProps={{ paper: { className: "external-sheet" } }}
        sx={{ display: { md: "none" } }}
        onClose={() => setSheetOpen(false)}
      >
        <Box className="external-sheet-handle" />
        <Box className="external-sheet-account">{accountCard}</Box>
        <Box className="external-sheet-grid">
          {visibleNavigation.map((item) => {
            const Icon = item.icon;
            return (
              <NavLink
                className={isItemActive(item, location.pathname) ? "external-sheet-item is-active" : "external-sheet-item"}
                key={item.path}
                to={item.path}
                onClick={() => setSheetOpen(false)}
              >
                <Icon />
                <span>{t(item.labelKey)}</span>
              </NavLink>
            );
          })}
        </Box>
        <Divider sx={{ my: 1.5 }} />
        <Stack direction={{ xs: "column", sm: "row" }} spacing={1.5}>
          <Button color="inherit" fullWidth startIcon={<KeyOutlined />} onClick={() => { setSheetOpen(false); navigate("/change-password"); }}>{t("auth.changePassword")}</Button>
          <Button fullWidth startIcon={<LogoutOutlined />} variant="outlined" onClick={handleLogout}>{t("auth.logout")}</Button>
        </Stack>
      </Drawer>
    </Box>
  );
}
