import { Link, Outlet, useLocation, useNavigate } from "react-router-dom"
import { useEffect, useState } from "react"
import type { ReactNode } from "react"
import {
  ApiOutlined,
  AuditOutlined,
  BarChartOutlined,
  BellOutlined,
  CalendarOutlined,
  CloudServerOutlined,
  CrownOutlined,
  DashboardOutlined,
  DollarOutlined,
  DownOutlined,
  FileSearchOutlined,
  FolderOpenOutlined,
  GiftOutlined,
  InfoCircleOutlined,
  LinkOutlined,
  LogoutOutlined,
  MessageOutlined,
  ProductOutlined,
  ProfileOutlined,
  SettingOutlined,
  ShopOutlined,
  SyncOutlined,
  TeamOutlined,
  TrophyOutlined,
  UserOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import { Avatar, Button, Dropdown, Layout, Menu, Space, Typography, theme } from "antd"
import { useAdminAuth } from "../contexts/AdminAuthContext"
import BrandLogo from "../../components/BrandLogo"
import { useBranding } from "../../contexts/BrandingContext"
import AdminNotificationBell from "./AdminNotificationBell"

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

type NavItem = {
  key: string
  label: string
  icon?: ReactNode
  children?: NavItem[]
}

const navItems: NavItem[] = [
  { key: "/admin", label: "仪表盘", icon: <DashboardOutlined /> },
  {
    key: "user",
    label: "用户与会员",
    icon: <TeamOutlined />,
    children: [
      { key: "/admin/users", label: "用户管理", icon: <UserOutlined /> },
      { key: "/admin/membership", label: "会员与伙伴", icon: <CrownOutlined /> },
    ],
  },
  {
    key: "sales",
    label: "销售与代理",
    icon: <ShopOutlined />,
    children: [
      { key: "/admin/service-orders", label: "服务订单", icon: <FileSearchOutlined /> },
      { key: "/admin/activities", label: "活动管理", icon: <CalendarOutlined /> },
      { key: "/admin/promo-codes", label: "优惠券管理", icon: <GiftOutlined /> },
      { key: "/admin/mall", label: "积分商城", icon: <ShopOutlined /> },
      { key: "/admin/agents", label: "代理管理", icon: <TeamOutlined /> },
      { key: "/admin/agent-tiers", label: "代理档位", icon: <TrophyOutlined /> },
      { key: "/admin/agent-settlements", label: "代理结算", icon: <DollarOutlined /> },
      { key: "/admin/affiliate", label: "AFF 渠道", icon: <BarChartOutlined /> },
    ],
  },
  {
    key: "product",
    label: "产品与资源",
    icon: <ProductOutlined />,
    children: [
      { key: "/admin/product-catalog", label: "分类与组", icon: <FolderOpenOutlined /> },
      { key: "/admin/products", label: "产品管理", icon: <ProductOutlined /> },
      { key: "/admin/product-integration", label: "商品对接", icon: <LinkOutlined /> },
      { key: "/admin/provision-plugins", label: "开通接口", icon: <ApiOutlined /> },
      { key: "/admin/instances", label: "实例管理", icon: <CloudServerOutlined /> },
      { key: "/admin/cloud-servers", label: "魔方云节点", icon: <CloudServerOutlined /> },
      { key: "/admin/upstream-actions", label: "资源审计", icon: <AuditOutlined /> },
    ],
  },
  {
    key: "finance",
    label: "财务",
    icon: <WalletOutlined />,
    children: [
      { key: "/admin/finance", label: "财务管理", icon: <WalletOutlined /> },
    ],
  },
  {
    key: "ticket",
    label: "工单",
    icon: <MessageOutlined />,
    children: [
      { key: "/admin/tickets", label: "工单列表", icon: <MessageOutlined /> },
      { key: "/admin/tickets/departments", label: "工单部门", icon: <MessageOutlined /> },
      { key: "/admin/tickets/templates", label: "回复模板", icon: <ProfileOutlined /> },
    ],
  },
  {
    key: "system",
    label: "系统",
    icon: <SettingOutlined />,
    children: [
      { key: "/admin/announcements", label: "公告管理", icon: <BellOutlined /> },
      { key: "/admin/tasks", label: "任务中心", icon: <SyncOutlined /> },
      { key: "/admin/plugin-diagnostics", label: "插件诊断", icon: <FileSearchOutlined /> },
      { key: "/admin/notification-plugins", label: "功能插件", icon: <MessageOutlined /> },
      { key: "/admin/settings", label: "系统设置", icon: <SettingOutlined /> },
      { key: "/admin/frontend-config", label: "前端配置", icon: <SettingOutlined /> },
      { key: "/admin/system-info", label: "系统信息", icon: <InfoCircleOutlined /> },
    ],
  },
]

type FlatNavItem = { key: string; label: string; icon?: ReactNode; parentKey?: string }

function flattenNavItems(items: NavItem[], parentKey?: string): FlatNavItem[] {
  const result: FlatNavItem[] = []
  for (const item of items) {
    if (item.children?.length) {
      result.push(...flattenNavItems(item.children, item.key))
    } else if (item.key.startsWith("/admin")) {
      result.push({ key: item.key, label: item.label, icon: item.icon, parentKey })
    }
  }
  return result
}

const flatNavItems = flattenNavItems(navItems)

function selectedNavKey(pathname: string) {
  const matched = [...flatNavItems]
    .sort((a, b) => b.key.length - a.key.length)
    .find((item) => pathname === item.key || pathname.startsWith(`${item.key}/`))
  return matched?.key ?? "/admin"
}

export default function AdminLayout() {
  const { token } = theme.useToken()
  const { admin, logout } = useAdminAuth()
  const { site_name } = useBranding()
  const location = useLocation()
  const navigate = useNavigate()

  const displayName = admin?.nickname || admin?.username || "Admin"
  const selectedKey = selectedNavKey(location.pathname)
  const currentNav = flatNavItems.find((item) => item.key === selectedKey)
  const currentParentKey = currentNav?.parentKey
  const [openKeys, setOpenKeys] = useState<string[]>(
    () => currentParentKey ? [currentParentKey] : [],
  )

  useEffect(() => {
    if (!currentParentKey) return
    setOpenKeys((previous) => (
      previous.includes(currentParentKey)
        ? previous
        : [...previous, currentParentKey]
    ))
  }, [currentParentKey, selectedKey])

  const handleNavClick = (info: { key: string }) => navigate(info.key)
  const handleUserMenuClick = (info: { key: string }) => {
    if (info.key === "logout") logout()
  }

  return (
    <Layout style={{ minHeight: "100vh", background: "#fff" }}>
      <Sider
        width={232}
        theme="light"
        breakpoint="lg"
        collapsedWidth={0}
        style={{
          borderInlineEnd: `1px solid ${token.colorBorderSecondary}`,
          background: "#fff",
          position: "sticky",
          top: 0,
          height: "100vh",
          overflow: "auto",
        }}
      >
        <Link to="/admin" style={{ height: 64, display: "flex", alignItems: "center", gap: 10, paddingInline: 20 }}>
          <Avatar shape="square" size={36} src={undefined} icon={<BrandLogo />} style={{ background: token.colorBgContainer }} />
          <Space orientation="vertical" size={0}>
            <Text strong>{site_name}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>Admin Console</Text>
          </Space>
        </Link>

        <Menu
          mode="inline"
          selectedKeys={[selectedKey]}
          openKeys={openKeys}
          onOpenChange={(keys: string[]) => setOpenKeys(keys)}
          items={navItems}
          onClick={handleNavClick}
          style={{ borderInlineEnd: 0 }}
        />
      </Sider>

      <Layout style={{ background: "#fff" }}>
        <Header
          style={{
            height: 64,
            paddingInline: 24,
            background: token.colorBgContainer,
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            position: "sticky",
            top: 0,
            zIndex: 20,
          }}
        >
          <Space size={10}>
            <span style={{ color: token.colorPrimary, fontSize: 18 }}>{currentNav?.icon}</span>
            <Text strong style={{ fontSize: 16 }}>{currentNav?.label ?? "后台管理"}</Text>
          </Space>

          <Space size={16}>
            <AdminNotificationBell />

            <Dropdown
              trigger={["click"]}
              menu={{
                items: [
                  { key: "profile", icon: <UserOutlined />, label: "管理员资料" },
                  { type: "divider" },
                  { key: "logout", icon: <LogoutOutlined />, label: "退出登录", danger: true },
                ],
                onClick: handleUserMenuClick,
              }}
            >
              <Button type="text">
                <Space>
                  <Avatar size="small" icon={<UserOutlined />}>
                    {displayName.charAt(0).toUpperCase()}
                  </Avatar>
                  <Text>{displayName}</Text>
                  <DownOutlined style={{ fontSize: 12 }} />
                </Space>
              </Button>
            </Dropdown>
          </Space>
        </Header>

        <Content style={{ padding: 24, background: "#fff" }}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  )
}
