import {
  AlertOutlined,
  ApartmentOutlined,
  AuditOutlined,
  BankOutlined,
  BookOutlined,
  ContactsOutlined,
  CreditCardOutlined,
  DashboardOutlined,
  FileTextOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MessageOutlined,
  PieChartOutlined,
  ShopOutlined,
  SafetyCertificateOutlined,
  UserSwitchOutlined,
} from '@ant-design/icons';
import { Avatar, Button, Dropdown, Flex, Layout, Menu, Space, Spin, Typography } from 'antd';
import type { MenuProps } from 'antd';
import { useState } from 'react';
import { Navigate, Outlet, useLocation, useNavigate } from 'react-router';
import type { components } from '../api/schema.generated';
import { useAuth } from '../auth/AuthProvider';

const { Header, Sider, Content } = Layout;
const navigation = [
  { key: '/', icon: <DashboardOutlined />, label: '经营概览', permission: 'platform:dashboard:view' },
  { type: 'group' as const, label: '业务运营', children: [
    { key: '/tenants', icon: <ApartmentOutlined />, label: '租户管理', permissions: ['platform:tenant:manage'] },
    { key: '/subscriptions', icon: <ShopOutlined />, label: '订阅与应收', permissions: ['platform:saas-catalog:manage', 'platform:saas-billing:manage'] },
    { key: '/usage', icon: <PieChartOutlined />, label: '用量计费', permissions: ['platform:saas-billing:manage'] },
    { key: '/dunning', icon: <FileTextOutlined />, label: '收款与催缴', permissions: ['platform:billing:notification', 'platform:saas-billing:manage'] },
    { key: '/refunds', icon: <BankOutlined />, label: '退款处理', permissions: ['platform:saas-billing:manage'] },
  ] },
  { type: 'group' as const, label: '内容资产', children: [
    { key: '/question-banks', icon: <BookOutlined />, label: '公共题库', permissions: ['platform:question-bank:manage'] },
  ] },
  { type: 'group' as const, label: '平台服务', children: [
    { key: '/crm', icon: <ContactsOutlined />, label: 'CRM 服务', permissions: ['platform:crm:read'] },
    { key: '/sms', icon: <MessageOutlined />, label: '短信服务', permissions: ['platform:sms:read'] },
    { key: '/payments', icon: <CreditCardOutlined />, label: '支付服务', permissions: ['platform:payment:read'] },
  ] },
  { type: 'group' as const, label: '安全与系统', children: [
    { key: '/staff', icon: <UserSwitchOutlined />, label: '员工与角色', permissions: ['platform:staff:manage', 'platform:role:manage'] },
    { key: '/audit', icon: <AuditOutlined />, label: '审计日志', permissions: ['platform:audit:view'] },
    { key: '/alerts', icon: <AlertOutlined />, label: '审计告警', permissions: ['platform:audit:view'] },
    { key: '/operations', icon: <DashboardOutlined />, label: '运行中心', permissions: ['platform:operations:view'] },
    { key: '/approvals', icon: <SafetyCertificateOutlined />, label: '审批中心', permissions: ['platform:approval:view'] },
    { key: '/configuration', icon: <ApartmentOutlined />, label: '配置中心', permissions: ['platform:configuration:manage'] },
    { key: '/notifications', icon: <MessageOutlined />, label: '通知中心', permissions: ['platform:notification:manage'] },
  ] },
];

type BackofficeMenuItem = components['schemas']['BackofficeMenuItem'];

const backendMenuPathAliases: Record<string, string> = {
  '/platform/dashboard': '/',
  '/platform/saas': '/subscriptions',
  '/platform/payment-settings': '/payments',
};

export function frontendPathForMenu(path: string): string {
  const normalizedPath = path.length > 1 ? path.replace(/\/+$/, '') : path;
  if (backendMenuPathAliases[normalizedPath]) return backendMenuPathAliases[normalizedPath];
  if (normalizedPath.startsWith('/platform/')) return normalizedPath.slice('/platform'.length);
  return normalizedPath;
}

export function visibleNavigationPaths(
  menus: readonly BackofficeMenuItem[],
  hasPermission: (...permissions: string[]) => boolean,
): string[] {
  const enabledPaths = new Set(menus
    .filter((menu) => menu.isActive && menu.path)
    .map((menu) => frontendPathForMenu(menu.path as string)));
  return navigation.flatMap((item) => {
    if ('permission' in item && item.permission && item.key) {
      return enabledPaths.has(item.key) && hasPermission(item.permission) ? [item.key] : [];
    }
    return (item.children || [])
      .filter((child) => enabledPaths.has(child.key) && hasPermission(...child.permissions))
      .map((child) => child.key);
  });
}

function visibleNavigation(
  menus: readonly BackofficeMenuItem[],
  hasPermission: (...permissions: string[]) => boolean,
): MenuProps['items'] {
  const items: NonNullable<MenuProps['items']> = [];
  const visiblePaths = new Set(visibleNavigationPaths(menus, hasPermission));
  const menuByPath = new Map(menus
    .filter((menu) => menu.isActive && menu.path)
    .map((menu) => [frontendPathForMenu(menu.path as string), menu]));
  for (const item of navigation) {
    if ('permission' in item && item.permission && item.key) {
      if (visiblePaths.has(item.key)) items.push({ key: item.key, icon: item.icon, label: menuByPath.get(item.key)?.title || item.label });
      continue;
    }
    if (!item.children) continue;
    const children = item.children.filter((child) => visiblePaths.has(child.key))
      .map(({ permissions: _, ...child }) => ({ ...child, label: menuByPath.get(child.key)?.title || child.label }));
    if (children.length > 0) items.push({ type: 'group', label: item.label, children });
  }
  return items;
}

const pageTitles: Record<string, string> = {
  '/': '经营概览', '/tenants': '租户开通', '/subscriptions': '订阅与应收', '/billing': '订阅与应收',
  '/usage': '用量计费', '/dunning': '收款与催缴', '/refunds': '退款处理', '/question-banks': '公共题库', '/crm': 'CRM 服务',
  '/sms': '短信服务', '/payments': '支付服务', '/staff': '员工与角色', '/audit': '审计日志', '/alerts': '审计告警', '/operations': '运行中心', '/approvals': '审批中心', '/configuration': '配置中心', '/notifications': '通知中心',
};

export function AppLayout() {
  const auth = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  if (auth.loading) return <div className="full-screen-loading"><Spin size="large" /></div>;
  if (!auth.user) return <Navigate to="/login" replace state={{ from: location.pathname }} />;
  const displayName = auth.user.name || auth.user.phone || auth.user.email || '平台管理员';
  return (
    <Layout className="app-shell">
      <Sider theme="light" collapsible collapsed={collapsed} collapsedWidth={76} trigger={null} width={248} className="app-sider">
        <div className="sider-brand">
          <div className="brand-mark"><img src="/logo.png" alt="Logo" /></div>
          {!collapsed && <div className="brand-copy"><strong>恭学题库</strong><span>平台管理中心</span></div>}
        </div>
        <div className="sider-navigation"><Menu theme="light" mode="inline" selectedKeys={[location.pathname]} items={visibleNavigation(auth.bootstrap?.menus || [], auth.hasPermission)} onClick={({ key }) => navigate(key)} /></div>
        <div className="sider-footer">
          <Button type="text" block icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={() => setCollapsed((value) => !value)}>{collapsed ? null : '收起导航'}</Button>
        </div>
      </Sider>
      <Layout>
        <Header className="app-header">
          <Typography.Text className="header-page-title">{pageTitles[location.pathname] || '平台管理'}</Typography.Text>
          <Dropdown
            menu={{ items: [{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', onClick: () => void auth.logout() }] }}
            trigger={['click']}
          >
            <Flex align="center" gap={10} className="user-menu">
              <Avatar>{String(displayName).slice(0, 1)}</Avatar>
              <Space direction="vertical" size={0}>
                <Typography.Text strong>{displayName}</Typography.Text>
                <Typography.Text type="secondary" className="user-role">平台管理</Typography.Text>
              </Space>
            </Flex>
          </Dropdown>
        </Header>
        <Content className="app-content"><Outlet /></Content>
      </Layout>
    </Layout>
  );
}
