import { useState } from 'react'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { Layout, Menu, Avatar, Dropdown, Button } from 'antd'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HomeOutlined,
  FileTextOutlined,
  MessageOutlined,
  ExperimentOutlined,
  FolderOpenOutlined,
  HistoryOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
} from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { ProjectSelector } from '../components/ProjectSelector'
import { CreateProjectDialog } from '../components/CreateProjectDialog'
import { EditProjectDialog } from '../components/EditProjectDialog'

const { Header, Sider, Content } = Layout

// 12个智能体配置（已按PRD更正）
export const AGENTS = [
  // 选题阶段
  { id: 'topic-evaluation', name: '选题评价智能体', icon: '🎯', enabled: true },
  { id: 'scientific-question', name: '科学问题梳理智能体', icon: '🔬', enabled: false },
  { id: 'picos-construction', name: 'PICOS构建智能体', icon: '📋', enabled: false },
  
  // 研究设计阶段
  { id: 'observation-design', name: '观察指标设计智能体', icon: '📊', enabled: false },
  { id: 'crf-development', name: 'CRF制定智能体', icon: '📝', enabled: false },
  { id: 'sample-size', name: '样本量计算智能体', icon: '🔢', enabled: false },
  { id: 'protocol-writing', name: '临床研究方案撰写智能体', icon: '📄', enabled: false },
  
  // 论文撰写阶段
  { id: 'paper-polishing', name: '论文润色智能体', icon: '✨', enabled: false },
  { id: 'paper-translation', name: '论文翻译智能体', icon: '🌐', enabled: false },
  { id: 'methodology-review', name: '方法学评审智能体', icon: '🔍', enabled: false },
  { id: 'journal-methodology-review', name: '期刊方法学评审智能体', icon: '📑', enabled: false },
  { id: 'journal-guidelines-review', name: '期刊稿约评审智能体', icon: '✅', enabled: false },
]

const MainLayout = () => {
  const [collapsed, setCollapsed] = useState(false)
  const navigate = useNavigate()
  const location = useLocation()

  // 菜单项配置
  const menuItems: MenuProps['items'] = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: '首页',
    },
    {
      key: '/review',
      icon: <FileTextOutlined />,
      label: '稿件审查',
    },
    {
      key: '/chat',
      icon: <MessageOutlined />,
      label: '智能问答',
    },
    {
      key: 'agents',
      icon: <ExperimentOutlined />,
      label: '智能体',
      children: AGENTS.map((agent) => ({
        key: `/agent/${agent.id}`,
        label: `${agent.icon} ${agent.name}`,
        disabled: !agent.enabled,
      })),
    },
    {
      key: '/knowledge',
      icon: <FolderOpenOutlined />,
      label: '知识库管理',
    },
    {
      key: '/history',
      icon: <HistoryOutlined />,
      label: '历史记录',
    },
  ]

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人中心',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '设置',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ]

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

  const handleUserMenuClick = ({ key }: { key: string }) => {
    if (key === 'logout') {
      console.log('退出登录')
      // TODO: 实现登出逻辑
    }
  }

  return (
    <Layout style={{ height: '100vh' }}>
      {/* 侧边栏 */}
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        theme="light"
        width={240}
        style={{ overflow: 'auto' }}
      >
        {/* Logo区域 */}
        <div
          style={{
            height: 64,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: collapsed ? 18 : 20,
            fontWeight: 'bold',
            color: '#1890ff',
            borderBottom: '1px solid #f0f0f0',
          }}
        >
          {collapsed ? '🏥' : '🏥 AI临床研究'}
        </div>

        {/* 项目选择器 */}
        {!collapsed && <ProjectSelector />}

        {/* 导航菜单 */}
        <Menu
          mode="inline"
          selectedKeys={[location.pathname]}
          defaultOpenKeys={['agents']}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ borderRight: 0 }}
        />
      </Sider>

      {/* 主内容区 */}
      <Layout>
        {/* 头部 */}
        <Header
          style={{
            padding: '0 24px',
            background: '#fff',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            borderBottom: '1px solid #f0f0f0',
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />

          <Dropdown menu={{ items: userMenuItems, onClick: handleUserMenuClick }} placement="bottomRight">
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar icon={<UserOutlined />} />
              <span>研究员</span>
            </div>
          </Dropdown>
        </Header>

        {/* 内容区 */}
        <Content
          style={{
            margin: 0,
            padding: 0,
            background: '#fff',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <Outlet />
        </Content>
      </Layout>

      {/* 对话框组件 */}
      <CreateProjectDialog />
      <EditProjectDialog />
    </Layout>
  )
}

export default MainLayout
