import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import SplashPage from '../pages/SplashPage';

interface Props {
  component: React.ComponentType<any>;
  path: string | string[];
  exact?: boolean;
}

const BYPASS_AUTH = false;

const ProtectedRouteLoader: React.FC = () => (
  <SplashPage title="Opening Kumusha" />
);

const ProtectedRoute: React.FC<Props> = ({ component: Component, ...rest }) => {
  const { user, profile, profileStatus } = useAuth();

  return (
    <Route
      {...rest}
      render={(props) => {
        if (!user) {
          return <Redirect to="/auth" />;
        }
        if (profileStatus === 'loading') {
          return <ProtectedRouteLoader />;
        }
        if (profileStatus === 'missing') {
          return <Redirect to="/setup-profile" />;
        }
        return <Component {...props} />;
      }}
    />
  );
};

export default ProtectedRoute;
