'use client';

import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { isAuthenticated, getUser, clearAuth } from '@/lib/auth';

interface AuthGuardProps {
    children: React.ReactNode;
    allowedTypes?: ('agency_user' | 'customer' | 'superadmin')[];
}

export default function AuthGuard({ children, allowedTypes }: AuthGuardProps) {
    const router = useRouter();
    const pathname = usePathname();
    const [authorized, setAuthorized] = useState<boolean | null>(null);
    const [mounted, setMounted] = useState(false);

    useEffect(() => {
        setMounted(true);
    }, []);

    useEffect(() => {
        if (!mounted) return;

        const checkAuth = () => {
            const isAuth = isAuthenticated();
            const user = getUser();

            if (!isAuth) {
                setAuthorized(false);
                if (pathname !== '/login') {
                    router.push('/login?error=unauthorized');
                }
                return;
            }

            // Verificar tipo de usuário se especificado
            if (allowedTypes && user) {
                const userType = user.user_type;
                if (!userType || !allowedTypes.includes(userType)) {
                    console.warn(`🚫 Access denied for user type: ${userType}. Allowed: ${allowedTypes}`);
                    setAuthorized(false);

                    // Redirecionar para o dashboard apropriado se estiver no lugar errado
                    if (userType === 'customer') {
                        router.push('/cliente/dashboard');
                    } else {
                        router.push('/login?error=forbidden');
                    }
                    return;
                }
            }

            setAuthorized(true);
        };

        checkAuth();

        // Listener para logout em outras abas
        const handleStorageChange = (e: StorageEvent) => {
            if (e.key === 'token' || e.key === 'user') {
                checkAuth();
            }
        };

        window.addEventListener('storage', handleStorageChange);
        return () => window.removeEventListener('storage', handleStorageChange);
    }, [router, pathname, mounted]);

    // Enquanto verifica, mostra loading
    if (!mounted || authorized === null) {
        return (
            <div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
                <div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
            </div>
        );
    }

    if (!authorized) {
        return (
            <div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
                <div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
            </div>
        );
    }

    return <>{children}</>;
}
