import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { usePermissions } from "@/hooks/usePermissions";
import type { UserRole } from "@/types/auth";

interface Props {
  allowedRoles?: UserRole[];
  requiredPermissions?: string[];
}

function getRoleDashboard(role: UserRole): string {
  switch (role) {
    case "student":
      return "/student/dashboard";
    case "teacher":
      return "/teacher/dashboard";
    case "admin":
    case "developer":
      return "/admin/dashboard";
    case "corporate":
    case "mastercorporate":
    case "agent":
      return "/admin/platform";
    default:
      return "/login";
  }
}

export default function ProtectedRoute({ allowedRoles, requiredPermissions }: Props) {
  const { user, isAuthenticated, isLoading } = useAuth();
  const { hasAllPermissions, isLoading: permissionsLoading } = usePermissions();

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (!isAuthenticated || !user) {
    return <Navigate to="/login" replace />;
  }

  if (allowedRoles && !allowedRoles.includes(user.user_type)) {
    return <Navigate to={getRoleDashboard(user.user_type)} replace />;
  }

  if (requiredPermissions && requiredPermissions.length > 0) {
    if (permissionsLoading) {
      return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      );
    }

    if (!hasAllPermissions(requiredPermissions)) {
      return <Navigate to={getRoleDashboard(user.user_type)} replace />;
    }
  }

  return <Outlet />;
}
