import { useLocation, useNavigate } from 'react-router-dom'
import { Layout, Menu, Dropdown, Avatar } from 'antd'
import {
  AppstoreOutlined, MessageOutlined, HistoryOutlined, TeamOutlined,
  FileTextOutlined, BarChartOutlined, SettingOutlined, LogoutOutlined, UserOutlined,
} from '@ant-design/icons'
import { useAuth } from '@/stores/auth'

const { Sider } = Layout

const menuItems = [
  { key: '/agent/dashboard', icon: <AppstoreOutlined />, label: '工作台' },
  { key: '/agent/chat-history', icon: <HistoryOutlined />, label: '对话记录' },
  { key: '/agent/customers', icon: <TeamOutlined />, label: '客户管理' },
  { key: '/agent/knowledge', icon: <FileTextOutlined />, label: '知识库' },
  { key: '/agent/statistics', icon: <BarChartOutlined />, label: '数据统计' },
  { key: '/agent/settings', icon: <SettingOutlined />, label: '系统设置' },
]

const AgentSidebar = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const { user, logout } = useAuth()
  const visibleMenuItems = menuItems.filter(item => {
    if (item.key === '/agent/statistics') return user?.role === 'admin' || user?.role === 'supervisor'
    if (item.key === '/agent/settings') return user?.role === 'admin'
    return true
  })

  const selectedKey = visibleMenuItems.find(item => location.pathname.startsWith(item.key))?.key || '/agent/dashboard'

  const handleLogout = () => {
    logout()
    navigate('/login', { replace: true })
  }

  return (
    <Sider width={220} className="!bg-white border-r border-neutral-200 flex flex-col">
      <div className="h-14 flex items-center px-5 border-b border-neutral-100">
        <MessageOutlined className="text-lg text-[#2563eb] mr-2.5" />
        <span className="text-base font-semibold text-neutral-900">客服云</span>
      </div>
      <Menu
        mode="inline"
        selectedKeys={[selectedKey]}
        items={visibleMenuItems}
        onClick={({ key }) => navigate(key)}
        className="border-e-0 mt-2 flex-1"
      />
      <div className="border-t border-neutral-100 p-3">
        <Dropdown
          menu={{ items: [{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', onClick: handleLogout }] }}
          trigger={['click']}
        >
          <div className="flex items-center gap-2 cursor-pointer hover:bg-neutral-50 rounded p-1.5">
            <Avatar size={28} icon={<UserOutlined />} className="!bg-blue-100 !text-blue-500" />
            <div className="min-w-0">
              <div className="text-xs font-medium text-neutral-700 truncate">{user?.nickname || '客服'}</div>
              <div className="text-xs text-neutral-400">在线</div>
            </div>
          </div>
        </Dropdown>
      </div>
    </Sider>
  )
}

export default AgentSidebar
