import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { XProvider } from "@ant-design/x";
import zhCN_X from "@ant-design/x/locale/zh_CN";
import { App as AntApp, Layout } from "antd";
import zhCN from "antd/locale/zh_CN";
import { useMemo } from "react";

import type { ConsoleShellProps } from "./types";

import { APP } from "../../../../shared/app";
import { useMeta } from "../../hooks/use-meta";
import { useSidebarCollapsed } from "../../hooks/use-sidebar-collapsed";
import { useThemePreference } from "../../hooks/use-theme-preference";
import { buildThemeConfig } from "../../theme/theme-config";
import { Sidebar } from "../Sidebar";
import { ConsoleOutlet } from "./ConsoleOutlet";

const { Content, Header, Sider } = Layout;

export function ConsoleShell({ headerExtra, menuItems, title }: ConsoleShellProps) {
  const { effectiveTheme } = useThemePreference();
  const { collapsed, setCollapsed } = useSidebarCollapsed();
  const { data: meta } = useMeta();

  const versionDisplay = meta?.version ? `v${meta.version}` : null;
  const locale = useMemo(() => ({ ...zhCN, ...zhCN_X }), []);

  return (
    <XProvider locale={locale} theme={buildThemeConfig(effectiveTheme)}>
      <AntApp>
        <Layout className="app-layout">
          <Header className="app-header">
            <div className="app-header-left">
              <span className="app-brand-group">
                <span className="app-brand">{APP.title}</span>
                {versionDisplay && <span className="app-version">{versionDisplay}</span>}
                <span className="app-console-title">{title}</span>
              </span>
            </div>
            <div className="app-header-right">{headerExtra}</div>
          </Header>
          <Layout>
            <Sider
              collapsed={collapsed}
              collapsedWidth={64}
              collapsible
              onCollapse={(c) => setCollapsed(c)}
              theme={effectiveTheme === "dark" ? "dark" : "light"}
              trigger={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              width={232}
            >
              <Sidebar menuItems={menuItems} />
            </Sider>
            <Layout>
              <Content className="app-content">
                <ConsoleOutlet />
              </Content>
            </Layout>
          </Layout>
        </Layout>
      </AntApp>
    </XProvider>
  );
}
