import { useQuery } from "@apollo/client";
import React from "react";
import { Redirect, Route, RouteProps } from "react-router-dom";
import { CurrentUser } from "./graphql/generated/types";
import { CURRENT_USER } from "./graphql/queries";

type Props = {
  component: (props: any) => JSX.Element;
  otherProps?: any;
} & RouteProps;

function AuthRoute(props: Props) {
  const { component: Component, otherProps: otherProps, ...rest } = props;
  const { loading: meLoading, error: meError, data: meData } = useQuery<
    CurrentUser
  >(CURRENT_USER);

  if (meLoading) {
    return <div>loading</div>;
  } else if (meError) {
    console.log(meError);
    return <div>Error</div>;
  }

  // has data
  const { me } = meData as CurrentUser;

  let isAuthed = false;
  if (me) {
    isAuthed = true;
  }

  if (!isAuthed) {
    return <Redirect to="/login" />;
  }

  return (
    <Route
      {...rest}
      render={(props) => <Component {...props} {...otherProps} user={me} />}
    />
  );
}

export default AuthRoute;
