'use client';

import React, { useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';

/**
 * D. Web管理前端 - 主布局
 *
 * 左侧Sidebar导航 + 顶部Header + 主内容区
 * 覆盖 D1-D8 所有管理模块的路由结构
 */

interface NavItem {
  key: string;
  icon: string;
  label: string;
  children?: NavItem[];
  badge?: number;
}

const navItems: NavItem[] = [
  { key: 'dashboard', icon: '📊', label: '运营总览' },
  {
    key: 'issuers', icon: '🏢', label: '发行方管理',
    children: [
      { key: 'issuers/review', icon: '', label: '入驻审核' },
      { key: 'issuers/list', icon: '', label: '发行方列表' },
      { key: 'issuers/coupons', icon: '', label: '券审核' },
    ],
  },
  {
    key: 'users', icon: '👤', label: '用户管理',
    children: [
      { key: 'users/list', icon: '', label: '用户列表' },
      { key: 'users/kyc', icon: '', label: 'KYC审核', badge: 5 },
    ],
  },
  {
    key: 'trading', icon: '💱', label: '交易监控',
    children: [
      { key: 'trading/realtime', icon: '', label: '实时交易流' },
      { key: 'trading/stats', icon: '', label: '交易统计' },
      { key: 'trading/orders', icon: '', label: '订单管理' },
    ],
  },
  {
    key: 'risk', icon: '🛡️', label: '风控中心',
    children: [
      { key: 'risk/dashboard', icon: '', label: '风险仪表盘', badge: 3 },
      { key: 'risk/suspicious', icon: '', label: '可疑交易' },
      { key: 'risk/blacklist', icon: '', label: '黑名单管理' },
      { key: 'risk/ofac', icon: '', label: 'OFAC筛查日志' },
    ],
  },
  {
    key: 'compliance', icon: '📋', label: '合规报表',
    children: [
      { key: 'compliance/sar', icon: '', label: 'SAR管理' },
      { key: 'compliance/ctr', icon: '', label: 'CTR管理' },
      { key: 'compliance/audit', icon: '', label: '审计日志' },
      { key: 'compliance/reports', icon: '', label: '监管报表' },
    ],
  },
  {
    key: 'system', icon: '⚙️', label: '系统管理',
    children: [
      { key: 'system/admins', icon: '', label: '管理员账号' },
      { key: 'system/config', icon: '', label: '系统配置' },
      { key: 'system/contracts', icon: '', label: '合约管理' },
      { key: 'system/monitor', icon: '', label: '系统监控' },
    ],
  },
  { key: 'disputes', icon: '⚖️', label: '争议处理', badge: 8 },
  { key: 'coupons', icon: '🎫', label: '券管理' },
  { key: 'finance', icon: '💰', label: '财务管理' },
  { key: 'chain', icon: '⛓️', label: '链上监控' },
  { key: 'reports', icon: '📈', label: '报表中心' },
  { key: 'merchant', icon: '🏪', label: '商户核销' },
  { key: 'agent', icon: '🤖', label: '代理面板' },
  { key: 'insurance', icon: '🛡️', label: '保险管理' },
  {
    key: 'analytics', icon: '📊', label: '数据分析',
    children: [
      { key: 'analytics/users', icon: '', label: '用户分析' },
      { key: 'analytics/coupons', icon: '', label: '券分析' },
      { key: 'analytics/market-maker', icon: '', label: '做市商分析' },
      { key: 'analytics/consumer-protection', icon: '', label: '消费者保护' },
    ],
  },
];

export const AdminLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const pathname = usePathname();
  const router = useRouter();
  const [collapsed, setCollapsed] = useState(false);

  // Derive activeKey from current pathname
  const activeKey = pathname.replace(/^\//, '') || 'dashboard';

  // Auto-expand parent nav items based on current path
  const getInitialExpanded = () => {
    const expanded: string[] = [];
    navItems.forEach(item => {
      if (item.children && item.children.some(c => activeKey.startsWith(c.key) || activeKey === item.key)) {
        expanded.push(item.key);
      }
    });
    return expanded;
  };
  const [expandedKeys, setExpandedKeys] = useState<string[]>(getInitialExpanded);

  const toggleExpand = (key: string) => {
    setExpandedKeys(prev =>
      prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
    );
  };

  return (
    <div style={{ display: 'flex', height: '100vh', background: 'var(--color-bg)' }}>
      {/* Sidebar */}
      <aside
        style={{
          width: collapsed ? 'var(--sidebar-collapsed-width)' : 'var(--sidebar-width)',
          background: 'var(--color-surface)',
          borderRight: '1px solid var(--color-border-light)',
          display: 'flex',
          flexDirection: 'column',
          transition: 'width 0.2s ease',
          overflow: 'hidden',
        }}
      >
        {/* Logo */}
        <div style={{
          height: 'var(--header-height)',
          display: 'flex',
          alignItems: 'center',
          padding: '0 20px',
          borderBottom: '1px solid var(--color-border-light)',
        }}>
          <div style={{
            width: 32, height: 32,
            background: 'linear-gradient(135deg, #6C5CE7, #9B8FFF)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            fontWeight: 700,
            fontSize: 16,
          }}>
            G
          </div>
          {!collapsed && (
            <span style={{
              marginLeft: 12,
              font: 'var(--text-h3)',
              color: 'var(--color-primary)',
            }}>
              Genex Admin
            </span>
          )}
        </div>

        {/* Nav */}
        <nav style={{ flex: 1, overflow: 'auto', padding: '12px 8px' }}>
          {navItems.map(item => (
            <div key={item.key}>
              <button
                onClick={() => {
                  if (item.children) {
                    toggleExpand(item.key);
                  } else {
                    router.push('/' + item.key);
                  }
                }}
                style={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  padding: '10px 12px',
                  border: 'none',
                  borderRadius: 'var(--radius-sm)',
                  background: activeKey === item.key || activeKey.startsWith(item.key + '/') ? 'var(--color-primary-surface)' : 'transparent',
                  color: activeKey === item.key || activeKey.startsWith(item.key + '/') ? 'var(--color-primary)' : 'var(--color-text-secondary)',
                  cursor: 'pointer',
                  font: 'var(--text-label)',
                  marginBottom: 2,
                  textAlign: 'left',
                }}
              >
                <span style={{ fontSize: 18, width: 24 }}>{item.icon}</span>
                {!collapsed && (
                  <>
                    <span style={{ flex: 1, marginLeft: 8 }}>{item.label}</span>
                    {item.badge && (
                      <span style={{
                        background: 'var(--color-error)',
                        color: 'white',
                        borderRadius: 'var(--radius-full)',
                        padding: '1px 6px',
                        fontSize: 10,
                        fontWeight: 600,
                      }}>
                        {item.badge}
                      </span>
                    )}
                    {item.children && (
                      <span style={{ fontSize: 12, transform: expandedKeys.includes(item.key) ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}>
                        ▸
                      </span>
                    )}
                  </>
                )}
              </button>
              {/* Sub items */}
              {item.children && expandedKeys.includes(item.key) && !collapsed && (
                <div style={{ marginLeft: 36, marginBottom: 4 }}>
                  {item.children.map(sub => (
                    <button
                      key={sub.key}
                      onClick={() => router.push('/' + sub.key)}
                      style={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        padding: '8px 12px',
                        border: 'none',
                        borderRadius: 'var(--radius-sm)',
                        background: activeKey === sub.key ? 'var(--color-primary-surface)' : 'transparent',
                        color: activeKey === sub.key ? 'var(--color-primary)' : 'var(--color-text-tertiary)',
                        cursor: 'pointer',
                        font: 'var(--text-body-sm)',
                        textAlign: 'left',
                      }}
                    >
                      <span style={{ flex: 1 }}>{sub.label}</span>
                      {sub.badge && (
                        <span style={{
                          background: 'var(--color-error)',
                          color: 'white',
                          borderRadius: 'var(--radius-full)',
                          padding: '1px 6px',
                          fontSize: 10,
                        }}>
                          {sub.badge}
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>

        {/* Collapse toggle */}
        <button
          onClick={() => setCollapsed(!collapsed)}
          style={{
            padding: 12,
            border: 'none',
            borderTop: '1px solid var(--color-border-light)',
            background: 'none',
            cursor: 'pointer',
            color: 'var(--color-text-tertiary)',
          }}
        >
          {collapsed ? '→' : '← 收起'}
        </button>
      </aside>

      {/* Main Content */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Header */}
        <header style={{
          height: 'var(--header-height)',
          background: 'var(--color-surface)',
          borderBottom: '1px solid var(--color-border-light)',
          display: 'flex',
          alignItems: 'center',
          padding: '0 24px',
          justifyContent: 'space-between',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <input
              placeholder="搜索用户/订单/交易..."
              style={{
                width: 320,
                height: 36,
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-full)',
                padding: '0 16px',
                font: 'var(--text-body)',
                background: 'var(--color-gray-50)',
                outline: 'none',
              }}
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {/* AI Agent Button */}
            <button style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              padding: '6px 14px',
              border: '1px solid var(--color-primary)',
              borderRadius: 'var(--radius-full)',
              background: 'var(--color-primary-surface)',
              color: 'var(--color-primary)',
              cursor: 'pointer',
              font: 'var(--text-label-sm)',
            }}>
              ✨ AI 助手
            </button>
            {/* Notifications */}
            <button style={{
              position: 'relative',
              border: 'none',
              background: 'none',
              cursor: 'pointer',
              fontSize: 20,
            }}>
              🔔
              <span style={{
                position: 'absolute',
                top: -2, right: -2,
                width: 8, height: 8,
                background: 'var(--color-error)',
                borderRadius: '50%',
              }} />
            </button>
            {/* Admin avatar */}
            <div style={{
              width: 32, height: 32,
              borderRadius: '50%',
              background: 'var(--color-primary)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'white',
              fontSize: 14,
              fontWeight: 600,
            }}>
              A
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main style={{ flex: 1, overflow: 'auto', padding: 24 }}>
          {children}
        </main>
      </div>
    </div>
  );
};
