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);
  const [ locations, setLocations ] = useState([]);

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

    const effect = async () => {
      const res = await window.fetch(
        `${base}/api/v1/locations/`, {
        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;
      }
      setLocations(data.map(location => {
        const fields = Object.getOwnPropertyNames(location)
        .map(field => <div key={field}
          style={{
            display: 'flex', 
            flexDirection: 'row',
            alignItems: 'flex-start',
            width: '100%'
          }}>
          <div style={{
            display: 'flex', 
            alignSelf: 'flex-start', 
            fontWeight: 'bold', 
            minWidth: '8rem' 
          }}>{field}</div>
            <div style={{ 
              display: 'flex', 
              alignSelf: 'flex-start',
              textAlign: 'left'
            }}>
              {location[field]}
            </div>
          </div>
        );
        return <div key={location.id} style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}>{ fields }</div>;
      }));
    };
    effect();
  }, [user, setGroup, groupId, csrfToken]);


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

    const effect = async () => {
      const res = await window.fetch(
        `${base}/api/v1/groups/${groupId}/events`, {
        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;
      }
      setGroup(data);
    };
    effect();
  }, [user, setGroup, groupId, csrfToken]);

  return (
    <Paper className="Group" style={{
      display: 'flex',
      flexDirection: 'column'
    }}>
      <GlobalContext.Provider value={{user, setUser}}>
        { error && <div>{error}</div>}
        { !error && <>
          <div>Group: {groupId}</div>
          <div>Locations</div>
          { locations }
        </> }
      </GlobalContext.Provider>
    </Paper>
  );
}

export default Group;
