'use client';

import React, { useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import LoadingSpinner from '@/components/LoadingSpinner';

export default function AuthenticatedLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { isAuthenticated, isLoading, user, logout } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      console.log('AuthenticatedLayout: User not authenticated, redirecting to login.');
      router.replace('/login');
    }
  }, [isAuthenticated, isLoading, router]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-100">
        <LoadingSpinner />
      </div>
    );
  }

  if (!isAuthenticated || !user) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-100">
        <LoadingSpinner />
      </div>
    );
  }

  const handleLogout = async () => {
    try {
      await logout();
      router.push('/login'); 
    } catch (error) {
      console.error('注销失败:', error);
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-gray-100">
      <header className="bg-white shadow-md w-full sticky top-0 z-50">
        <nav className="container mx-auto px-6 py-3 flex justify-between items-center">
          <div>
            <Link href={user.role === 'admin' ? '/admin/dashboard' : '/dashboard'} 
                  className="text-xl font-bold text-blue-700 hover:text-blue-900 transition-colors">
              充电机器人管理系统
            </Link>
          </div>
          <div className="flex items-center space-x-4">
            {user && (
              <span className="text-gray-700 text-sm">
                欢迎, <span className="font-medium">{user.username}</span> ({user.role === 'admin' ? '管理员' : '用户'})
              </span>
            )}
            {user.role === 'admin' && (
              <Link href="/admin/mqtt-logs" 
                    className="text-sm text-blue-600 hover:text-blue-800 hover:underline transition-colors">
                MQTT日志
              </Link>
            )}
            <button
              onClick={handleLogout}
              className="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded-md text-sm font-semibold transition duration-150 ease-in-out shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50"
            >
              注销
            </button>
          </div>
        </nav>
      </header>
      <main className="flex-grow container mx-auto py-8 px-4 md:px-6 lg:px-8">
        {children}
      </main>
      <footer className="bg-gray-800 text-white text-center p-4 mt-auto w-full">
        <p className="text-sm">&copy; {new Date().getFullYear()} 充电机器人管理系统. 保留所有权利.</p>
      </footer>
    </div>
  );
} 