import { useAuth } from "react-oidc-context";
import { Navigate, Outlet } from "react-router-dom";

export default function AuthGuard() {
  const auth = useAuth();

  if (auth.isLoading || auth.activeNavigator) {
    return <div>Loading...</div>;
  }

  if (auth.error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center p-4 text-center">
        <div className="mb-4 text-red-500">
          <h2 className="text-xl font-bold">Authentication Error</h2>
          <p>{auth.error.message}</p>
        </div>
        <button
          type="button"
          onClick={() => void auth.signinRedirect()}
          className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
        >
          Start Login Again
        </button>
      </div>
    );
  }

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

  return <Outlet />;
}
