import React from 'react';
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import type { RootState } from '../../store/store';

interface ProtectedRouteProps {
  children: React.ReactNode;
  allowedRoles: Array<'admin' | 'client' | 'vendor' | 'ADMIN' | 'CLIENT' | 'VENDOR'>;
  redirectTo?: string;
}

/**
 * ProtectedRoute Component
 * Ensures only authenticated users with specific roles can access certain routes
 * Redirects to appropriate dashboard if user role doesn't match allowed roles
 */
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  allowedRoles,
  redirectTo = '/dashboard/client',
}) => {
  const { isAuthenticated, user } = useSelector((state: RootState) => state.auth);

  // If user is not authenticated, redirect to login
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  // If user is authenticated but role is not allowed, redirect to specified path
  // Compare roles case-insensitively to handle backend casing (e.g., "ADMIN" vs "admin")
  if (
    user?.userRole &&
    !allowedRoles.some((r) => r.toLowerCase() === user.userRole!.toLowerCase())
  ) {
    return <Navigate to={redirectTo} replace />;
  }

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

export default ProtectedRoute;
