import React, { useEffect, useState } from 'react';

function AddGameNight(props) {
  const [expanded, setExpanded] = useState(false);
  const [gameName, setGameName] = useState("");
  const [date, setDate] = useState(null);

  const handleAddGamenight = (event) => {
    props.onChange({
      game: gameName,
      datetime: date
    }).then((result) => {
      if(result) {
        setExpanded(false);
        setGameName("");
        setDate(null);
      }
    });
    event.preventDefault();
  };

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

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

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

  if(expanded) {
    return (
      <div className="Add-GameNight">
        <form onSubmit={handleAddGamenight}>
          <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>
            <input id="datetime" name="datetime" type="datetime-local"
              value={date}
              onChange={handleDateChange} />
  
            <input type="submit" value="Submit" />
          </fieldset>
        </form>
        <button onClick={() => setExpanded(false)}>Discard</button>
      </div>        
    );
  } else {
    return (
      <button onClick={() => setExpanded(true)}>Expand</button>
    );
  }
}

export default AddGameNight