import { useState } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { Layout, Menu, Avatar, Dropdown, Typography } from 'antd';
import type { MenuProps } from 'antd';
import {
  DashboardOutlined,
  BookOutlined,
  RobotOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  BarChartOutlined,
  FileTextOutlined,
  AuditOutlined,
  LineChartOutlined,
  MessageOutlined,
  ClusterOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { useAuth } from '../hooks/useAuth';

const { Header, Sider, Content } = Layout;
const { Text } = Typography;

const menuItems: MenuProps['items'] = [
  {
    key: '/',
    icon: <DashboardOutlined />,
    label: '仪表盘',
  },
  {
    key: '/knowledge',
    icon: <BookOutlined />,
    label: '知识库',
  },
  {
    key: '/experience',
    icon: <RobotOutlined />,
    label: '系统经验',
  },
  {
    key: 'analytics-group',
    icon: <BarChartOutlined />,
    label: '数据分析',
    children: [
      {
        key: '/analytics',
        icon: <LineChartOutlined />,
        label: '统计分析',
      },
      {
        key: '/reports',
        icon: <FileTextOutlined />,
        label: '财务报表',
      },
      {
        key: '/audit',
        icon: <AuditOutlined />,
        label: '审计日志',
      },
    ],
  },
  {
    key: '/users',
    icon: <UserOutlined />,
    label: '用户管理',
  },
  {
    key: '/conversations',
    icon: <MessageOutlined />,
    label: '对话管理',
  },
  {
    key: '/tenants',
    icon: <ClusterOutlined />,
    label: '租户管理',
  },
  {
    key: '/mcp',
    icon: <ApiOutlined />,
    label: 'MCP 服务器',
  },
  {
    key: '/settings',
    icon: <SettingOutlined />,
    label: '系统设置',
  },
];

// Analytics submenu paths
const analyticsRoutes = ['/analytics', '/reports', '/audit'];

export function MainLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { admin, logout } = useAuth();

  // Auto-expand analytics submenu when on analytics pages
  const defaultOpenKeys = analyticsRoutes.includes(location.pathname)
    ? ['analytics-group']
    : [];

  const handleMenuClick = (e: { key: string }) => {
    navigate(e.key);
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人设置',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ];

  const handleUserMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'logout') {
      logout();
      navigate('/login');
    }
  };

  return (
    <Layout className="min-h-screen">
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        theme="light"
        className="shadow-sm"
      >
        <div className="h-16 flex items-center justify-center border-b">
          <Text strong className="text-lg">
            {collapsed ? 'iC' : 'iConsulting'}
          </Text>
        </div>
        <Menu
          mode="inline"
          selectedKeys={[location.pathname]}
          defaultOpenKeys={defaultOpenKeys}
          items={menuItems}
          onClick={handleMenuClick}
          className="border-none"
        />
      </Sider>
      <Layout>
        <Header className="bg-white px-4 flex items-center justify-between shadow-sm">
          <div
            className="cursor-pointer text-lg"
            onClick={() => setCollapsed(!collapsed)}
          >
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </div>
          <Dropdown
            menu={{ items: userMenuItems, onClick: handleUserMenuClick }}
            placement="bottomRight"
          >
            <div className="flex items-center cursor-pointer">
              <Avatar icon={<UserOutlined />} className="mr-2" />
              <Text>{admin?.name || 'Admin'}</Text>
            </div>
          </Dropdown>
        </Header>
        <Content className="bg-gray-100 min-h-0 overflow-auto">
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
}
