'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard, Users, BookOpen, MessageSquare,
  FileText, Wrench, ShoppingCart, Building2, MessageCircle,
  BarChart3, Settings, Bell, LogOut, ChevronDown, Layout,
} from 'lucide-react';
import { AdminAIAssistant } from '@/components/admin-ai-assistant';

const sidebarLinks = [
  { href: '/admin', label: '仪表盘', icon: LayoutDashboard },
  { href: '/admin/analytics', label: '数据分析', icon: BarChart3 },
  { href: '/admin/users', label: '用户管理', icon: Users },
  { href: '/admin/courses', label: '课程管理', icon: BookOpen },
  { href: '/admin/prompts', label: '提示词管理', icon: MessageSquare },
  { href: '/admin/contents', label: '内容管理', icon: FileText },
  { href: '/admin/tools', label: '工具管理', icon: Wrench },
  { href: '/admin/orders', label: '订单管理', icon: ShoppingCart },
  { href: '/admin/enterprise', label: '企业版管理', icon: Building2 },
  { href: '/admin/comments', label: '评论审核', icon: MessageCircle },
  { href: '/admin/operations/banners', label: 'Banner管理', icon: Layout },
  { href: '/admin/operations/notifications', label: '推送管理', icon: Bell },
  { href: '/admin/settings/roles', label: '角色权限', icon: Settings },
  { href: '/admin/settings/config', label: '系统配置', icon: Settings },
];

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [checked, setChecked] = useState(false);
  const [adminInfo, setAdminInfo] = useState<{ username: string; role?: string } | null>(null);

  const isLoginPage = pathname === '/admin/login';

  useEffect(() => {
    const token = localStorage.getItem('adminToken');
    if (!token && !isLoginPage) {
      router.replace('/admin/login');
    } else {
      // 获取管理员信息
      try {
        const info = localStorage.getItem('adminInfo');
        if (info) setAdminInfo(JSON.parse(info));
      } catch {}
      setChecked(true);
    }
  }, [isLoginPage, router]);

  function handleLogout() {
    localStorage.removeItem('adminToken');
    localStorage.removeItem('adminInfo');
    router.replace('/admin/login');
  }

  function isActive(href: string) {
    if (href === '/admin') return pathname === '/admin';
    return pathname.startsWith(href) && href !== '/admin';
  }

  if (isLoginPage) return <>{children}</>;
  if (!checked) return <div className="min-h-screen bg-background" />;

  return (
    <div className="min-h-screen bg-background">
      {/* 顶部导航栏 */}
      <header className="h-14 border-b border-border bg-card flex items-center justify-between px-4 sticky top-0 z-50">
        <div className="flex items-center gap-4">
          <Link href="/admin" className="flex items-center gap-2">
            <div className="w-8 h-8 bg-brand-600 rounded-lg flex items-center justify-center text-white font-bold">Y</div>
            <span className="text-lg font-bold text-foreground">管理后台</span>
          </Link>
          <span className="text-sm text-muted-foreground hidden sm:inline">宇之然AI平台管理系统</span>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 px-3 py-1.5 bg-muted rounded-lg">
            <div className="w-6 h-6 bg-brand-600 rounded-full flex items-center justify-center text-white text-xs">
              {adminInfo?.username?.charAt(0) || 'A'}
            </div>
            <span className="text-sm text-foreground">{adminInfo?.username || '管理员'}</span>
            <span className="text-xs text-muted-foreground">({adminInfo?.role || '超级管理员'})</span>
          </div>
          <button
            onClick={handleLogout}
            className="flex items-center gap-2 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-lg transition-colors"
          >
            <LogOut className="w-4 h-4" />
            <span>退出</span>
          </button>
        </div>
      </header>

      <div className="flex">
        {/* 左侧菜单 */}
        <aside className="w-56 border-r border-border bg-card shrink-0 hidden md:block" style={{ minHeight: 'calc(100vh - 3.5rem)' }}>
          <nav className="p-3 space-y-1">
            {sidebarLinks.map((link) => {
              const Icon = link.icon;
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  className={`flex items-center gap-3 px-3 py-2.5 text-sm rounded-lg transition-colors ${
                    isActive(link.href)
                      ? 'bg-accent text-foreground font-semibold'
                      : 'text-muted-foreground hover:text-foreground hover:bg-accent'
                  }`}
                >
                  <Icon className="h-4 w-4" />
                  <span>{link.label}</span>
                </Link>
              );
            })}
          </nav>
        </aside>
        {/* 主内容区 */}
        <main className="flex-1 overflow-auto">{children}</main>
      </div>
      <AdminAIAssistant />
    </div>
  );
}