'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import Link from 'next/link';
import { 
  Truck, 
  LayoutDashboard, 
  Package, 
  Users, 
  LogOut, 
  Loader2,
  Menu,
  X,
  ChevronLeft,
  Settings,
  FileText,
  Image,
  HelpCircle,
  Globe
} from 'lucide-react';
import { AdminContext } from '@/contexts/admin-context';

interface Admin {
  id: string;
  username: string;
  name: string;
  role: string;
}

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [admin, setAdmin] = useState<Admin | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // 检查登录状态
  useEffect(() => {
    // 登录页面不需要检查
    if (pathname === '/admin/login') {
      setIsLoading(false);
      return;
    }

    const checkAuth = async () => {
      try {
        const response = await fetch('/api/admin/me');
        const data = await response.json();

        if (!data.authenticated) {
          router.push('/admin/login');
          return;
        }

        setAdmin(data.admin);
      } catch {
        router.push('/admin/login');
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, [router, pathname]);

  // 退出登录
  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      await fetch('/api/admin/logout', { method: 'POST' });
      router.push('/admin/login');
    } finally {
      setIsLoggingOut(false);
    }
  };

  // 导航项
  const navItems = [
    { icon: LayoutDashboard, label: '仪表盘', href: '/admin' },
    { icon: Package, label: '订单管理', href: '/admin/orders' },
    { icon: Users, label: '客户管理', href: '/admin/customers' },
    { icon: FileText, label: '服务内容', href: '/admin/services' },
    { icon: Image, label: '案例管理', href: '/admin/cases' },
    { icon: HelpCircle, label: '常见问题', href: '/admin/faqs' },
    { icon: Globe, label: '多语言内容', href: '/admin/i18n' },
  ];

  // 登录页面直接渲染
  if (pathname === '/admin/login') {
    return <>{children}</>;
  }

  // 加载中
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
      </div>
    );
  }

  return (
    <AdminContext.Provider value={{ admin, isLoading }}>
      <div className="min-h-screen bg-gray-100">
        {/* 顶部导航栏 */}
        <header className="fixed top-0 left-0 right-0 z-50 bg-white border-b border-gray-200 h-16">
          <div className="flex items-center justify-between h-full px-4">
            <div className="flex items-center gap-4">
              <button
                onClick={() => setSidebarOpen(!sidebarOpen)}
                className="lg:hidden p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg"
              >
                {sidebarOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
              </button>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center shadow-md border border-gray-100">
                  <img src="/images/logo.png" alt="欣琪国际货运" className="w-8 h-8 object-contain" />
                </div>
                <div className="hidden sm:block">
                  <h1 className="text-base font-bold text-gray-900">欣琪国际货运</h1>
                  <p className="text-xs text-gray-500">后台管理系统</p>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <Link
                href="/"
                className="hidden sm:flex items-center gap-2 px-3 py-2 text-sm text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
              >
                <ChevronLeft className="w-4 h-4" />
                前台首页
              </Link>
              <div className="flex items-center gap-3 pl-4 border-l border-gray-200">
                <div className="text-right hidden sm:block">
                  <p className="text-sm font-medium text-gray-900">{admin?.name}</p>
                  <p className="text-xs text-gray-500">{admin?.role === 'super_admin' ? '超级管理员' : '管理员'}</p>
                </div>
                <button
                  onClick={handleLogout}
                  disabled={isLoggingOut}
                  className="flex items-center gap-2 px-3 py-2 text-sm text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                >
                  {isLoggingOut ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <LogOut className="w-4 h-4" />
                  )}
                  <span className="hidden sm:inline">退出</span>
                </button>
              </div>
            </div>
          </div>
        </header>

        {/* 侧边栏遮罩 */}
        {sidebarOpen && (
          <div
            className="fixed inset-0 z-40 bg-black/50 lg:hidden"
            onClick={() => setSidebarOpen(false)}
          />
        )}

        {/* 侧边栏 */}
        <aside className={`fixed top-16 left-0 z-40 w-64 h-[calc(100vh-4rem)] bg-white border-r border-gray-200 transform transition-transform duration-200 lg:translate-x-0 ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        }`}>
          <nav className="p-4 space-y-1">
            {navItems.map((item) => {
              const isActive = pathname === item.href || 
                (item.href !== '/admin' && pathname.startsWith(item.href));
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-colors ${
                    isActive
                      ? 'bg-blue-50 text-blue-700'
                      : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                  }`}
                >
                  <item.icon className={`w-5 h-5 ${isActive ? 'text-blue-600' : 'text-gray-400'}`} />
                  <span className="font-medium">{item.label}</span>
                </Link>
              );
            })}
          </nav>
        </aside>

        {/* 主内容区 */}
        <main className="lg:ml-64 pt-16 min-h-screen">
          <div className="p-6">
            {children}
          </div>
        </main>
      </div>
    </AdminContext.Provider>
  );
}
