import React from 'react';
import { useAuth } from '@/lib/auth';

type Role = 'STUDENT' | 'ADMIN' | 'ORG_MEMBER' | 'ORG_ADMIN' | 'SUPER_ADMIN';

interface RoleGuardProps {
    children: React.ReactNode;
    allowedRoles?: Role[];
    requireSuperAdmin?: boolean;
    fallback?: React.ReactNode;
}

/**
 * RoleGuard component to conditionally render content based on user roles.
 * 
 * Usage:
 * <RoleGuard allowedRoles={['SUPER_ADMIN', 'ADMIN']}>
 *   <SecretComponent />
 * </RoleGuard>
 */
export const RoleGuard: React.FC<RoleGuardProps> = ({ 
    children, 
    allowedRoles, 
    requireSuperAdmin = false,
    fallback = null 
}) => {
    const { user } = useAuth();

    if (!user) return <>{fallback}</>;

    const userRole = user.role as Role;

    // Special case for Super Admin logic
    if (requireSuperAdmin) {
        if (userRole === 'SUPER_ADMIN' || userRole === 'ADMIN') {
            return <>{children}</>;
        }
        return <>{fallback}</>;
    }

    // Default role check
    if (allowedRoles && allowedRoles.length > 0) {
        if (allowedRoles.includes(userRole)) {
            return <>{children}</>;
        }
        return <>{fallback}</>;
    }

    return <>{children}</>;
};

export default RoleGuard;
