import { Navigate, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';

interface RoleGuardProps {
    children: React.ReactNode;
    allowedRoles?: string[];
    excludeRoles?: string[];
    redirectTo?: string;
}

export const RoleGuard: React.FC<RoleGuardProps> = ({
    children,
    allowedRoles,
    excludeRoles,
    redirectTo
}) => {
    const { user, isAuthenticated, loading } = useSelector((state: RootState) => state.auth);
    const location = useLocation();
    const normalizedRole = String((user as any)?.role || (user as any)?.roleCode || '').trim().toLowerCase();
    const normalizedAllowedRoles = (allowedRoles || []).map((r) => String(r).trim().toLowerCase());
    const normalizedExcludedRoles = (excludeRoles || []).map((r) => String(r).trim().toLowerCase());

    if (loading) {
        return <div className="flex h-screen items-center justify-center">Loading...</div>;
    }

    if (!isAuthenticated) {
        return <Navigate to="/admin-login" state={{ from: location }} replace />;
    }

    // Check excluded roles first (e.g. Block Prospective Dealer from main dashboard)
    if (excludeRoles && user && normalizedExcludedRoles.includes(normalizedRole)) {
        // If prospective dealer is excluded, redirect to their dashboard
        if (normalizedRole === 'prospective dealer') {
            return <Navigate to="/prospective-dashboard" replace />;
        }
        return <Navigate to={redirectTo || '/dashboard'} replace />;
    }

    // Check allowed roles (e.g. Only Prospective Dealer can see their dashboard)
    if (allowedRoles && user && !normalizedAllowedRoles.includes(normalizedRole)) {
        // If regular dealer tries to access prospective dashboard
        return <Navigate to={redirectTo || '/dashboard'} replace />;
    }

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