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

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 handleNameChange = (event) => {
    setGameName(event.target.value);
  };

  const handleDateChange = (event) => {
    setDate(event.target.value);
  };

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

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

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

      fetch('api/gamenight', 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>
          <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={(value) => { setDate(value) }} value={date} />
  
            <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