import {
  AlertOutlined,
  FileTextOutlined,
  FundOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SafetyOutlined,
  UserOutlined
} from "@ant-design/icons";
import { Layout, Menu } from "antd";
import type { ReactNode } from "react";
import { getVisibleAdminTabs, type AdminTab } from "../config/adminTabs";
import type { AdminColorMode } from "../config/adminTheme";

const ADMIN_SIDEBAR_COLLAPSED_KEY = "wespAdminSidebarCollapsed";

const TAB_ICONS: Record<AdminTab, ReactNode> = {
  users: <UserOutlined />,
  content: <FileTextOutlined />,
  security: <SafetyOutlined />,
  diagnostics: <AlertOutlined />,
  activity: <FundOutlined />
};

interface AdminSiderProps {
  tab: AdminTab;
  isSuperuser: boolean;
  collapsed: boolean;
  colorMode: AdminColorMode;
  onCollapse: (collapsed: boolean) => void;
  onSelect: (tab: AdminTab) => void;
}

export function readAdminSidebarCollapsedPreference(): boolean {
  if (typeof window === "undefined") {
    return true;
  }
  return localStorage.getItem(ADMIN_SIDEBAR_COLLAPSED_KEY) !== "0";
}

export function persistAdminSidebarCollapsedPreference(collapsed: boolean): void {
  localStorage.setItem(ADMIN_SIDEBAR_COLLAPSED_KEY, collapsed ? "1" : "0");
}

function isMobileViewport(): boolean {
  return typeof window !== "undefined" && window.matchMedia("(max-width: 768px)").matches;
}

export function AdminSider({
  tab,
  isSuperuser,
  collapsed,
  colorMode,
  onCollapse,
  onSelect
}: AdminSiderProps): JSX.Element {
  const items = getVisibleAdminTabs(isSuperuser).map((item) => ({
    key: item.id,
    icon: TAB_ICONS[item.id],
    label: <span className="wesp-menu-label">{item.label}</span>
  }));

  return (
    <Layout.Sider
      id="wesp-admin-sider"
      className="wesp-admin-sider"
      theme={colorMode}
      width={256}
      collapsed={collapsed}
      collapsedWidth={80}
      collapsible
      trigger={
        <div
          className="ant-layout-sider-trigger"
          role="button"
          tabIndex={0}
          aria-controls="wesp-admin-sider"
          aria-expanded={!collapsed}
          title={collapsed ? "Развернуть меню" : "Свернуть меню"}
        >
          <span className="wesp-sider-trigger-icon" aria-hidden="true">
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </span>
        </div>
      }
      onCollapse={(nextCollapsed) => {
        if (isMobileViewport()) {
          return;
        }
        onCollapse(nextCollapsed);
        persistAdminSidebarCollapsedPreference(nextCollapsed);
      }}
    >
      <Menu
        theme={colorMode}
        mode="inline"
        inlineCollapsed={collapsed}
        selectedKeys={[tab]}
        onClick={(event) => onSelect(event.key as AdminTab)}
        items={items}
      />
    </Layout.Sider>
  );
}

export type { AdminTab };
