import React, { useState, useEffect, useContext } from "react";
import Paper from '@mui/material/Paper';
import {
  useParams,
  useNavigate
} from "react-router-dom";

import './Group.css';
import { GlobalContext } from "./GlobalContext.js";
import { base } from "./Common.js";

function Group() {
  const { csrfToken, user, setUser } = useContext(GlobalContext);
  const groupId = useParams().group;
  const [ group, setGroup ] = useState(null);
  const [ error, setError ] = useState(null);

  useEffect(() => {
    if (!user || !groupId || !csrfToken) {
      return;
    }

    const effect = async () => {
      const res = await window.fetch(
        `${base}/api/v1/group/${groupId}/events`, {
        method: 'POST',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json',
          'CSRF-Token': csrfToken
        }
      });
      const data = await res.json();
      if (res.status >= 400) {
        setError(data.message ? data.message : res.statusText);
        return;
        }
      if (!data) {
        return;
      }
      setGroup(data);
    };
    effect();
  }, [user, setGroup, groupId, csrfToken]);

  return (
    <Paper className="Group">
      <GlobalContext.Provider value={{user, setUser}}>
        Group: {groupId}
      </GlobalContext.Provider>
    </Paper>
  );
}

export default Group;
