'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import Link from 'next/link';
import { 
  Truck, 
  Package, 
  User,
  Settings,
  LogOut,
  Loader2,
  ChevronLeft,
  ClipboardList,
  KeyRound,
  Mail,
  FileText
} from 'lucide-react';
import { UserContext, useUser } from '@/contexts/user-context';
import { useLanguage } from '@/i18n/LanguageContext';
import { LanguageSwitcherSimple } from '@/components/language-switcher';

interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string | null;
  company: string | null;
  created_at: string;
}

export default function UserLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const { t, locale } = useLanguage();
  const [customer, setCustomer] = useState<Customer | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // 检查登录状态
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const response = await fetch('/api/auth/me');
        const data = await response.json();

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

        setCustomer(data.customer);
      } catch (error) {
        console.error('Error:', error);
        router.push('/auth');
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, [router]);

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

  // 导航项
  const navItems = [
    {
      title: t.user.logistics,
      items: [
        { icon: Package, label: t.user.services, href: '/services' },
      ]
    },
    {
      title: t.user.orderManagement,
      items: [
        { icon: ClipboardList, label: t.user.orders, href: '/user/orders' },
      ]
    },
    {
      title: t.user.personalSettings,
      items: [
        { icon: User, label: t.user.editProfile, href: '/user/settings' },
        { icon: KeyRound, label: t.user.changePassword, href: '/user/settings/password' },
        { icon: Mail, label: t.user.changeEmail, href: '/user/settings/email' },
      ]
    },
  ];

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

  return (
    <UserContext.Provider value={{ customer, setCustomer, isLoading }}>
      <div className="min-h-screen bg-gray-50">
        {/* 顶部导航栏 */}
        <header className="fixed top-0 left-0 right-0 z-50 bg-white border-b border-gray-200">
          <div className="flex items-center justify-between h-16 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"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                </svg>
              </button>
              <Link href="/" className="flex items-center gap-2 text-gray-600 hover:text-blue-600 transition-colors">
                <ChevronLeft className="w-5 h-5" />
                <span className="hidden sm:inline">{t.user.backHome}</span>
              </Link>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-9 h-9 bg-white rounded-lg flex items-center justify-center border border-gray-100 shadow-sm">
                <img src="/images/logo.png" alt={t.common.logo} className="w-7 h-7 object-contain" />
              </div>
              <div className="hidden sm:block">
                <h1 className="text-base font-bold text-gray-900">{t.common.logo}</h1>
                <p className="text-xs text-gray-500">{t.nav.userCenter}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <LanguageSwitcherSimple />
              <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">{t.nav.logout}</span>
              </button>
            </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'
        }`}>
          <div className="flex flex-col h-full">
            {/* 用户信息 */}
            <div className="p-4 border-b border-gray-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                  <User className="w-5 h-5 text-blue-600" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-gray-900 truncate">{customer?.name}</p>
                  <p className="text-xs text-gray-500">{customer?.phone}</p>
                </div>
              </div>
            </div>

            {/* 导航菜单 */}
            <nav className="flex-1 p-4 overflow-y-auto">
              {navItems.map((group, groupIndex) => (
                <div key={groupIndex} className="mb-6">
                  <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2 px-3">
                    {group.title}
                  </h3>
                  <ul className="space-y-1">
                    {group.items.map((item, itemIndex) => {
                      const isActive = pathname === item.href;
                      return (
                        <li key={itemIndex}>
                          <Link
                            href={item.href}
                            onClick={() => setSidebarOpen(false)}
                            className={`flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors ${
                              isActive
                                ? 'bg-blue-50 text-blue-600'
                                : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                            }`}
                          >
                            <item.icon className="w-5 h-5" />
                            <span className="text-sm font-medium">{item.label}</span>
                          </Link>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              ))}
            </nav>

            {/* 底部退出按钮 */}
            <div className="p-4 border-t border-gray-100 lg:hidden">
              <button
                onClick={handleLogout}
                disabled={isLoggingOut}
                className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
              >
                <LogOut className="w-5 h-5" />
                <span className="text-sm font-medium">{t.nav.logout}</span>
              </button>
            </div>
          </div>
        </aside>

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