import React, { useEffect } from "react";
import { Typography } from "@material-ui/core";
import useStyles from "../useStyles";

import { useUserContext } from "../Contexts/UserContext";
import { useStatusContext } from "../Contexts/StatusContext";
import { parsePayload } from "../../utils/jwt";
import VehicleMap from "../VehicleMap";

const DEFAULT_GREETING = "Welcome";

const getGreeting = (token) => {
  if (!token || !token.idToken || !token.idToken.jwtToken)
    return DEFAULT_GREETING;

  const payload = parsePayload(token.idToken.jwtToken);

  if (!payload || !payload.given_name) return DEFAULT_GREETING;

  return `Welcome ${payload.given_name}!`;
};

const Home = () => {
  const classes = useStyles();
  const { token } = useUserContext();
  const greeting = getGreeting(token);
  const { setTitle } = useStatusContext();


  useEffect(() => {
    setTitle("Home");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className={classes.paper}>
      <Typography className={classes.homePageTitle} component="h1" variant="h5">
        {greeting}
      </Typography>
      <VehicleMap />
    </div>
  );
};

export default Home;
