import Cookies from "js-cookie";
import Router from "next/router";
import { useEffect } from "react";
import { gql, useLazyQuery } from "@apollo/client";

import * as cookieNames from "../lib/cookieNames";
import Dashboard from "../components/dashboard";
import Loading from "../components/loading";

const ME_QUERY = gql`
  query Me {
    me {
      id
      firstname
      email
      role
      teacher {
        id
      }
      student {
        id
      }
    }
  }
`;

const token = Cookies.get(cookieNames.TOKEN);

function Home(): JSX.Element {
  useEffect(() => {
    if (!token) {
      Router.push("/login");
    }
  });

  const [loadMe, { called, loading, data }] = useLazyQuery(ME_QUERY, {
    variables: { token },
  });

  if (!token) {
    return <></>;
  }

  if (called && loading) {
    return <Loading />;
  } else if (!called) {
    loadMe();
    return <Loading />;
  }

  return (
    <div>
      <Dashboard user={data.me} />
    </div>
  );
}

export default Home;
