import React, { useEffect, useState } from 'react';
import DateTime from 'react-datetime';
import GameAdder from './GameAdder';

import Autocomplete from '@mui/material/Autocomplete';

import "react-datetime/css/react-datetime.css";

function AddGameNight(props) {
  const [expanded, setExpanded] = useState(false);
  const [gameName, setGameName] = useState("");
  const [date, setDate] = useState(Date.now());
  const [gameList, setGameList] = useState([]); 
  
  const emptyUuid = "00000000-0000-0000-0000-000000000000";

  //temp hack: 
  props.games = [{id: emptyUuid, name: "mystic vale"}, {id: emptyUuid, name: "Crew"}];


  const handleNameChange = (event) => {
    setGameName(event.target.value);
  };

  const onDateChange = (date) => {
    setDate(date);
  };

  const onGamesListChange = (gameList) => {
    setGameList(gameList);
  }

  useEffect(() => {
    if(!expanded) {
      setGameName("");
      setDate(null);
    }
  }, [expanded]);

  const handleAddGamenight = (event) => {
    event.preventDefault();
    if (props.user !== null) {
      let input = {
        name: gameName,
        datetime: date,
        game_list: gameList,
      }

      const requestOptions = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${props.user.jwt}`
        },
        body: JSON.stringify(input)
      };

      fetch('api/gamenights', requestOptions)
        .then(response => response.json())
        .then(data => {
          if(data.result !== "Ok") {
            props.setFlash({
              type: "Error",
              message: data.message
            });
          } else {
            setExpanded(false);
            setGameName("");
            setDate(null);
          }
        })
        .then(() => props.refetchGamenights())
    }
    
  };

  if(expanded) {
    return (
      <div className="Add-GameNight">
        <form autoComplete="off" onSubmit={e => { e.preventDefault(); }}>
          <fieldset>
            <legend>Gamenight</legend>
  
            <label for="gamename">Game name:</label>
            <input id="gamename" name="gamename" type="text"
              value={gameName}
              onChange={handleNameChange} />
            <label for="datetime">date:</label>
            <DateTime id="datetime" onChange={onDateChange} value={date} />
  
            <GameAdder games={props.games} onChange={onGamesListChange}/>

            <button onClick={handleAddGamenight}>Submit</button>
          </fieldset>
        </form>
        <button onClick={() => setExpanded(false)}>Discard</button>
      </div>        
    );
  } else {
    return (
      <button onClick={() => setExpanded(true)}>Expand</button>
    );
  }
}

export default AddGameNight