'use client';

import * as React from 'react';
import Alert from '@mui/material/Alert';
import {useAuth} from "../../hooks/useAuth";
import {logger} from "../../lib/DefaultLogger";
import {paths} from "../../path";

export function GuestGuard({ children }) {
  const { auth, error, isLoading } = useAuth();
  const [isChecking, setIsChecking] = React.useState(true);

  const checkPermissions = async () => {
    if (isLoading) {
      return;
    }

    if (error) {
      setIsChecking(false);
      return;
    }

    if (auth) {
      logger.debug('[GuestGuard]: User is logged in, redirecting to dashboard');
      window.location.replace(paths.dashboard.overview);
      return;
    }

    setIsChecking(false);
  };

  React.useEffect(() => {
    checkPermissions().catch(() => {
      // noop
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps -- Expected
  }, [auth, error, isLoading]);

  if (isChecking) {
    return null;
  }

  if (error) {
    return <Alert color="error">{error}</Alert>;
  }

  return <React.Fragment>{children}</React.Fragment>;
}
