import { useMemo, useState } from "react"
import { Link, Outlet, useLocation, useNavigate } from "react-router-dom"
import type { MenuProps } from "antd"
import { Avatar, Badge, Button, Dropdown, Layout, Menu, Space, Spin, Typography } from "antd"
import NotificationBell from "../components/NotificationBell"
import {
  AppstoreOutlined,
  CloudServerOutlined,
  CrownOutlined,
  DashboardOutlined,
  FileTextOutlined,
  GiftOutlined,
  LogoutOutlined,
  MessageOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SafetyCertificateOutlined,
  SettingOutlined,
  ShareAltOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import { useAuth } from "../contexts/AuthContext"
import BrandLogo from "../components/BrandLogo"

const { Header, Sider, Content } = Layout
const { Text } = Typography
type MenuClickInfo = Parameters<NonNullable<MenuProps["onClick"]>>[0]

const NAV_ITEMS: MenuProps["items"] = [
  { key: "/dashboard", icon: <DashboardOutlined />, label: "仪表盘" },
  {
    key: "services",
    icon: <AppstoreOutlined />,
    label: "产品服务",
    children: [
      { key: "/control/server", icon: <CloudServerOutlined />, label: "服务器管理" },
      { key: "/control/security-groups", icon: <SafetyCertificateOutlined />, label: "安全组管理" },
      { key: "/store", icon: <ShoppingCartOutlined />, label: "购买服务" },
      { key: "/orders", icon: <FileTextOutlined />, label: "订单管理" },
      { key: "/finance", icon: <WalletOutlined />, label: "财务管理" },
    ],
  },
  { key: "/membership", icon: <CrownOutlined />, label: "会员中心" },
  { key: "/points-mall", icon: <GiftOutlined />, label: "积分商城" },
  { key: "/points-center", icon: <WalletOutlined />, label: "积分中心" },
  { key: "/promotion", icon: <ShareAltOutlined />, label: "推广中心" },
  { key: "/agent", icon: <ShareAltOutlined />, label: "代理中心" },
  {
    key: "support",
    icon: <MessageOutlined />,
    label: "支持服务",
    children: [
      { key: "/tickets", icon: <MessageOutlined />, label: "工单支持" },
    ],
  },
  { key: "/settings", icon: <SettingOutlined />, label: "账户设置" },
]

export default function DashboardLayout() {
  const { user, logout, isLoading } = useAuth()
  const location = useLocation()
  const navigate = useNavigate()
  const [collapsed, setCollapsed] = useState(false)

  const selectedKey = useMemo(() => {
    const path = location.pathname
    if (path.startsWith("/control/server")) return "/control/server"
    if (path.startsWith("/control/security-groups")) return "/control/security-groups"
    if (path.startsWith("/store")) return "/store"
    if (path.startsWith("/orders")) return "/orders"
    if (path.startsWith("/finance")) return "/finance"
    if (path.startsWith("/membership")) return "/membership"
    if (path.startsWith("/points-mall")) return "/points-mall"
    if (path.startsWith("/points-center")) return "/points-center"
    if (path.startsWith("/promotion")) return "/promotion"
    if (path.startsWith("/agent")) return "/agent"
    if (path.startsWith("/tickets")) return "/tickets"
    if (path.startsWith("/settings")) return "/settings"
    return "/dashboard"
  }, [location.pathname])

  const handleNavClick = ({ key }: MenuClickInfo) => {
    if (typeof key === "string" && key.startsWith("/")) navigate(key)
  }

  const handleUserMenuClick = ({ key }: MenuClickInfo) => {
    if (key === "logout") logout()
    if (key === "settings" || key === "profile") navigate("/settings")
  }

  const userMenu: MenuProps["items"] = [
    { key: "profile", icon: <UserOutlined />, label: "个人资料" },
    { key: "settings", icon: <SettingOutlined />, label: "账户设置" },
    { type: "divider" },
    { key: "logout", icon: <LogoutOutlined />, label: "退出登录", danger: true },
  ]

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center bg-white">
        <Spin size="large" tip="正在加载" />
      </div>
    )
  }

  return (
    <Layout style={{ minHeight: "100vh", background: "#fff" }}>
      <Sider
        width={232}
        collapsedWidth={72}
        collapsed={collapsed}
        onCollapse={setCollapsed}
        breakpoint="lg"
        style={{
          background: "#fff",
          borderRight: "1px solid #f0f0f0",
          position: "sticky",
          top: 0,
          height: "100vh",
          overflow: "auto",
        }}
      >
        <Link
          to="/"
          style={{
            height: 64,
            display: "flex",
            alignItems: "center",
            justifyContent: collapsed ? "center" : "flex-start",
            padding: collapsed ? 0 : "0 20px",
            borderBottom: "1px solid #f0f0f0",
          }}
        >
          <BrandLogo style={{ height: 36, width: "auto", objectFit: "contain" }} />
        </Link>

        <Menu
          mode="inline"
          selectedKeys={[selectedKey]}
          defaultOpenKeys={["services", "support"]}
          items={NAV_ITEMS}
          style={{ borderInlineEnd: 0, paddingTop: 12 }}
          onClick={handleNavClick}
        />
      </Sider>

      <Layout style={{ background: "#fff" }}>
        <Header
          style={{
            height: 64,
            padding: "0 24px",
            background: "#fff",
            borderBottom: "1px solid #f0f0f0",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            position: "sticky",
            top: 0,
            zIndex: 20,
          }}
        >
          <Space size={16}>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed((v) => !v)}
            />
            <div>
              <Text strong>控制台</Text>
              <Text type="secondary" style={{ marginLeft: 10, fontSize: 12 }}>
                云服务器与财务管理
              </Text>
            </div>
          </Space>

          <Space size={16}>
            <Text type="secondary" className="hidden sm:inline">
              余额 ¥{((user?.balance || 0) / 100).toFixed(2)}
            </Text>
            <Link to="/cart">
              <Badge count={0} size="small">
                <Button type="text" icon={<ShoppingCartOutlined />} />
              </Badge>
            </Link>
            <NotificationBell />
            <Dropdown
              menu={{
                items: userMenu,
                onClick: handleUserMenuClick,
              }}
              placement="bottomRight"
            >
              <Button type="text" style={{ height: 40 }}>
                <Space>
                  <Avatar size={28} icon={<UserOutlined />}>
                    {user?.username?.charAt(0).toUpperCase()}
                  </Avatar>
                  <span className="hidden md:inline">{user?.username}</span>
                </Space>
              </Button>
            </Dropdown>
          </Space>
        </Header>

        <Content style={{ background: "#fff", padding: 24 }}>
          <div className="qycw-page-enter" style={{ maxWidth: 1280, margin: "0 auto" }}>
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}
