import { ReactNode, useEffect } from 'react';
import { useRouter } from 'next/router';
import { useAuth } from '../hooks/useAuth';
import Sidebar from './Sidebar';

interface LayoutProps {
    children: ReactNode;
    requireAuth?: boolean;
    requireAdmin?: boolean;
}

export default function Layout({ children, requireAuth = true, requireAdmin = false }: LayoutProps) {
    const { user, loading, isAdmin } = useAuth();
    const router = useRouter();

    useEffect(() => {
        if (!loading) {
            if (requireAuth && !user) {
                router.push('/login');
            }
            if (requireAdmin && !isAdmin) {
                router.push('/dashboard');
            }
        }
    }, [user, loading, requireAuth, requireAdmin, isAdmin, router]);

    if (loading) {
        return (
            <div className="min-h-screen bg-dark-bg flex items-center justify-center">
                <div className="animate-spin w-10 h-10 border-4 border-brand-primary border-t-transparent rounded-full" />
            </div>
        );
    }

    if (requireAuth && !user) return null;

    return (
        <div className="min-h-screen bg-dark-bg">
            <Sidebar />
            <main className="ml-64 p-8">
                {children}
            </main>
        </div>
    );
}
