import React, { useState, useEffect, useContext } from "react";
import Paper from '@mui/material/Paper';
import Moment from 'react-moment';

import {
  useParams,
  useNavigate
} from "react-router-dom";

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

function Dashboard() {
  const { csrfToken, user, setUser } = useContext(GlobalContext);
  const [ groups, setGroups ] = useState([]);
  const [ error, setError ] = useState(null);

  useEffect(() => {
    if (!user || !csrfToken) {
      return;
    }
    const effect = async () => {
      const res = await window.fetch(
        `${base}/api/v1/groups`, {
        method: 'GET',
        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;
      }
      setGroups(data);
    }
    
    effect();
  }, [user, setGroups, csrfToken ]);

  return (
    <Paper className="Dashboard">
      <GlobalContext.Provider value={{user, setUser}}>
        <Paper style={{
          flexDirection: 'column',
          display: 'flex',
          width: '100%'
        }}>

        { groups.map((group) => {
          return <div key={group.id} style={{
            flexDirection: 'column',
            display: 'flex',
            alignItems: 'flex-start',
            padding: '0.5rem'
          }}>
            <div key={group.id} style={{
              fontWeight: 'bold'
            }}>{group.name}</div>
            { group.nextEvent &&
              <div>Next event <Moment fromNow date={group.nextEvent} /> on <Moment format={'MMMM Do YYYY, h: mm: ss a'} date={group.nextEvent}/>.</div>
            }
          </div>;
        }) }
        </Paper>
      </GlobalContext.Provider>
    </Paper>
  );
}

export default Dashboard;
