import { Link, NavLink, useLocation } from 'react-router'
import { Menu, Popover, Button } from 'antd'
import { CaretDownOutlined } from '@ant-design/icons'
import './AppHeader.scss'
import { useUserStore } from '@/stores/user'
import { logout } from '@/api/base'

export default function AppHeader({ title = 'AI数据分析实验室' }) {
  const location = useLocation()

  const user = useUserStore((state) => state.info)
  const name = user?.name || user?.username
  const avatar = user?.avatar || 'https://webapp-pub.ezijing.com/website/base/images/avatar.svg'

  const menus = [
    { name: '首页', path: '/' },
    { name: '我的实验', path: '/data' },
  ]

  const items = menus.map((item) => {
    return {
      label: <NavLink to={item.path}>{item.name}</NavLink>,
      key: item.path,
    }
  })

  const matchedKey =
    items.find((item) => location.pathname === item.key)?.key ||
    items
      .filter((item) => location.pathname.startsWith(item.key)) // 过滤所有前缀匹配的项
      .sort((a, b) => b.key.length - a.key.length)[0]?.key || // 按 key 长度排序，取最长的匹配项
    '/'

  const handleLogout = async () => {
    await logout()
    window.location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(window.location.origin)}`
  }

  return (
    <div className="app-header">
      <div className="app-header-left">
        <div className="logo">
          <Link to="/">
            <img src="https://webapp-pub.ezijing.com/website/base/logo.svg" />
          </Link>
        </div>
        <div className="line"></div>
        <h1 className="app-name">
          <Link to="/">{title}</Link>
        </h1>
      </div>
      <div className="app-header-nav">
        <Menu mode="horizontal" items={items} defaultSelectedKeys={[matchedKey]} />
      </div>
      <div className="app-header-right">
        <Popover
          content={
            <div className="app-header-user">
              <div className="app-header-user-avatar">
                <img src={avatar} />
              </div>
              <div className="app-header-user-main">
                <h3>{name}</h3>
                <p>{user?.email}</p>
              </div>
              <div className="app-header-user-buttons">
                <Button shape="round" onClick={handleLogout}>
                  退出登录
                </Button>
              </div>
            </div>
          }>
          <div className="user">
            <div className="avatar">
              <img src={avatar} />
            </div>
            <p>{name}</p>
            <CaretDownOutlined />
          </div>
        </Popover>
      </div>
    </div>
  )
}
