import type { MappedUser } from '~/src/lib/songwhipApi/users/types';
import type { FC, ReactElement } from 'react';
import type { UseAuthGuardProps } from './useAuthGuard';

import Box from '../Box';
import FadeOnMount from '../FadeOnMount';
import useAuthGuard from './useAuthGuard';

export interface AuthGuardProps extends UseAuthGuardProps {
  render: (params: { user: MappedUser }) => ReactElement;
}

/**
 * A wrapper component that checks login and subscription state providing
 * composable `guard` content which prompts users to upgrade or renew
 * pro subscriptions. When not logged in users are redirected to /login.
 */
const AuthGuard: FC<AuthGuardProps> = ({ render, ...props }) => {
  const guard = useAuthGuard(props);

  if (guard.content) {
    return (
      <Box coverParent centerContent>
        <Box maxWidth="45rem" fullWidth padding="2rem">
          {guard.content}
        </Box>
      </Box>
    );
  }

  // render the content if logged in, leave the caller to render
  return <FadeOnMount>{render({ user: guard.user })}</FadeOnMount>;
};

export default AuthGuard;
