import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { Spin } from "antd";
import { Role } from "@/constants/navLink.constants";

interface ProtectedRouteProps {
  children: React.ReactElement;
  roles: string[];
  permissionKey?: string;
}

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  roles,
  permissionKey,
}) => {
  const { isAuthenticated, user, loading } = useAuth();
  const location = useLocation();
  const accessList: string[] = user?.permissions || [];

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

  if (!isAuthenticated || !user) {
    return <Navigate to="/landing" state={{ from: location }} replace />;
  }

  if (
    !roles.includes(user.role) || // only allow if user role is in roles array
    (user.role === Role.STAFF &&
      permissionKey &&
      ![...accessList, "allUsers"].includes(permissionKey)) //only allow if user role is staff and has permission
  ) {
    return <Navigate to="/" replace />;
  }

  return children;
};


