import { useState } from 'react';
import type { ReactNode } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Button, Avatar, Dropdown } from '@arco-design/web-react';
import {
  IconDashboard,
  IconDesktop,
  IconFile,
  IconBug,
  IconThunderbolt,
  IconSettings,
  IconUser,
  IconMenuFold,
  IconMenuUnfold,
  IconPoweroff,
} from '@arco-design/web-react/icon';
import { useAuthStore } from '@/stores/auth';

const Sider = Layout.Sider;
const Header = Layout.Header;
const Content = Layout.Content;

interface MenuItem {
  key: string;
  label: string;
  icon?: ReactNode;
  children?: MenuItem[];
}

const menuConfig: MenuItem[] = [
  { key: 'dashboard', label: 'Dashboard', icon: <IconDashboard /> },
  { key: 'devices', label: '设备管理', icon: <IconDesktop /> },
  { key: 'charge-records', label: '充电记录', icon: <IconFile /> },
  { key: 'device-logs', label: '设备日志', icon: <IconBug /> },
  { key: 'energy', label: '能耗管理', icon: <IconThunderbolt /> },
  {
    key: 'settings',
    label: '系统设置',
    icon: <IconSettings />,
    children: [
      { key: 'settings/users', label: '用户管理' },
      { key: 'settings/roles', label: '角色权限' },
      { key: 'settings/operation-logs', label: '操作日志' },
    ],
  },
];

/** 菜单 key 到路由 path 的映射 */
const menuKeyToPath: Record<string, string> = {
  dashboard: '/dashboard',
  devices: '/devices',
  'charge-records': '/charge-records',
  'device-logs': '/device-logs',
  energy: '/energy',
  'settings/users': '/settings/users',
  'settings/roles': '/settings/roles',
  'settings/operation-logs': '/settings/operation-logs',
};

/** 路由 path 到菜单 key 的反向映射 */
const pathToMenuKey: Record<string, string> = {};
for (const [key, path] of Object.entries(menuKeyToPath)) {
  pathToMenuKey[path] = key;
}

export default function AdminLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuthStore();

  const selectedKeys = [pathToMenuKey[location.pathname] || ''];
  const openKeys = location.pathname.startsWith('/settings')
    ? ['settings']
    : undefined;

  const handleMenuClick = (key: string) => {
    const path = menuKeyToPath[key];
    if (path) navigate(path);
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const dropList = (
    <Menu>
      <Menu.Item key="logout" onClick={handleLogout}>
        <IconPoweroff style={{ marginRight: 8 }} />
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout style={{ height: '100%' }}>
      <Sider
        collapsed={collapsed}
        width={220}
        style={{ background: 'var(--color-bg-2)' }}
      >
        <div
          style={{
            height: 60,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontWeight: 600,
            fontSize: collapsed ? 16 : 20,
            color: 'var(--color-text-1)',
            borderBottom: '1px solid var(--color-border)',
          }}
        >
          {collapsed ? 'PMS' : '充电柜管理系统'}
        </div>
        <Menu
          style={{ border: 'none' }}
          selectedKeys={selectedKeys}
          defaultOpenKeys={openKeys}
          onClickMenuItem={handleMenuClick}
        >
          {menuConfig.map((item) =>
            item.children ? (
              <Menu.SubMenu key={item.key} title={<>{item.icon}{item.label}</>}>
                {item.children.map((child) => (
                  <Menu.Item key={child.key}>{child.label}</Menu.Item>
                ))}
              </Menu.SubMenu>
            ) : (
              <Menu.Item key={item.key}>
                {item.icon}{item.label}
              </Menu.Item>
            ),
          )}
        </Menu>
      </Sider>
      <Layout>
        <Header
          style={{
            height: 60,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '0 20px',
            background: 'var(--color-bg-2)',
            borderBottom: '1px solid var(--color-border)',
          }}
        >
          <Button
            shape="round"
            size="small"
            icon={collapsed ? <IconMenuUnfold /> : <IconMenuFold />}
            onClick={() => setCollapsed(!collapsed)}
          />
          <Dropdown droplist={dropList} trigger="click" position="br">
            <div
              style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}
            >
              <Avatar size={32} style={{ background: 'var(--color-primary-light-4)' }}>
                <IconUser />
              </Avatar>
              <span style={{ fontSize: 14 }}>{user?.name || '管理员'}</span>
            </div>
          </Dropdown>
        </Header>
        <Content
          style={{
            padding: 16,
            background: 'var(--color-fill-2)',
            overflow: 'auto',
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
}
