import { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetManagerTypes } from 'src/hooks/queryHooks/manager';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { UserPermissions, hasAllPermissions } from 'src/utils/permissions';

export type Props = {
  children: ReactNode;
  managerPermissions: UserPermissions[];
  nonManagerPermissions: UserPermissions[];
};

const ManagerGuard = (props: Props) => {
  const { children, managerPermissions, nonManagerPermissions } = props;
  const { permissions } = useAuth();
  const { isManager, isFetchingSubordinates } = useGetManagerTypes([]);
  const HugoThemeProvider = useHuGoTheme();

  const requiredPermissions = isManager
    ? managerPermissions
    : nonManagerPermissions;

  if (isFetchingSubordinates) {
    return (
      <HugoThemeProvider>
        <Stack
          sx={{
            alignItems: 'center',
            height: '100%',
            justifyContent: 'center',
          }}
        >
          <HuCircularProgress />
        </Stack>
      </HugoThemeProvider>
    );
  }

  if (!hasAllPermissions(permissions, requiredPermissions)) {
    return <Navigate to="/" />;
  }

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

export default ManagerGuard;
