import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addGenreToGlobalAction,resetGenresGlobal } from "../../redux/actions";
import axios from "axios";
import { useEffect } from "react";

const Form = () => {
  
  const globalGenres = useSelector((state)=>state.genres);

  const dispatch = useDispatch();

  const [form, setForm] = useState({
    name:"",
    description:"",
    platforms:"",
    image:"",
    releaseDate:"",
    rating:"",
    genres:[],

  })

  useEffect(() => {
  setForm((form) => ({ ...form, genres: globalGenres }));
  }, [globalGenres]);


  const [genres, setGenres] = useState("")
  const [nameGenres, setNameGenres] = useState([])

  const onChangeHandle = (event) => {
    const value = event.target.value;
    const property = event.target.name;
    setForm({...form, [property]:value})
  }
  
  const submitHandler = async (event) => {
    event.preventDefault();
    setForm({...form, genres: globalGenres})
    try {
    const response = await axios.post('http://localhost:3001/post/videogames', form);
    console.log('Formulario Enviado Exitosamente',response.data);
  } catch (error) {
    console.error(error);
  }
}
  

  const handleGenres = (event) => {
    const genre = JSON.parse(event.target.value);
    setGenres(genre); 
    
  };



  const addGenresToGlobal = (genres) => {
    dispatch(addGenreToGlobalAction(genres.value));
    setNameGenres([...nameGenres, genres.name]);
    setGenres("");

  }

  const resetGenresHandlerClick = () => {
    const emptyArray = []
    setNameGenres([])
    dispatch(resetGenresGlobal(emptyArray))
  }

  return (
    <form onSubmit={submitHandler}>
      <label>
        Nombre:
        <input
          name="name"
          type="text"
          value={form.name}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Descripcion:
        <input
          name="description"
          type="text"
          value={form.description}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Platform:
        <input
          name="platforms"
          type="text"
          value={form.platforms}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Imagen:
        <input
          name="image"
          type="text"
          value={form.image}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Fecha de Lanzamiento:
        <input
          name="releaseDate"
          type="date"
          value={form.releaseDate}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Calificacion:
        <input
          name="rating"
          type="number"
          value={form.rating}
          onChange={onChangeHandle}
        />
      </label>
      <label>
        Generos:
        <select onChange={handleGenres}>
          <option value="">Selecciona los generos</option>
          <option value={JSON.stringify({ name: 'Action', value: '1' })}>Action</option>
          <option value={JSON.stringify({ name: 'Indie', value: '2' })}>Indie</option>
          <option value={JSON.stringify({ name: 'Adventure', value: '3' })}>Adventure</option>
          <option value={JSON.stringify({ name: 'RPG', value: '4' })}>RPG</option>
          <option value={JSON.stringify({ name: 'Strategy', value: '5' })}>Strategy</option>
          <option value={JSON.stringify({ name: 'Shooter', value: '6' })}>Shooter</option>
          <option value={JSON.stringify({ name: 'Casual', value: '7' })}>Casual</option>
          <option value={JSON.stringify({ name: 'Simulation', value: '8' })}>Simulation</option>
          <option value={JSON.stringify({ name: 'Puzzle', value: '9' })}>Puzzle</option>
          <option value={JSON.stringify({ name: 'Arcade', value: '10' })}>Arcade</option>
          <option value={JSON.stringify({ name: 'Platformer', value: '11' })}>Platformer</option>
          <option value={JSON.stringify({ name: 'Massively Multiplayer', value: '12' })}>Massively Multiplayer</option>
          <option value={JSON.stringify({ name: 'Racing', value: '13' })}>Racing</option>
          <option value={JSON.stringify({ name: 'Sports', value: '14' })}>Sports</option>
          <option value={JSON.stringify({ name: 'Fighting', value: '15' })}>Fighting</option>
          <option value={JSON.stringify({ name: 'Family', value: '16' })}>Family</option>
          <option value={JSON.stringify({ name: 'Board Game', value: '17' })}>Board Games</option>
          <option value={JSON.stringify({ name: 'Educational', value: '18' })}>Educational</option>
          <option value={JSON.stringify({ name: 'Card', value: '19' })}>Card</option>
        </select>
      </label>
      <div>
        <button type="button" onClick={()=>{addGenresToGlobal(genres)}}>Agregar Genero</button>
      </div>
      <div>
        <button type="button" onClick={()=>{resetGenresHandlerClick()}}>Reset Generos</button>
      </div>
      <div>
        {nameGenres && nameGenres.map((genres,index) =>{
          return <h1 key={index}>{genres}</h1>
        })}
      </div>
      <div>
        <button type="submit">Enviar</button>
      </div>
    </form>
  );
};

export default Form;

ayudame a crear validaciones para mi form