import * as React from "react";
import { convertDateToDayName } from "./utils";
import { useRecipes } from "../../hooks";
import { useState } from "react";
import useSafeDispatch from "../../hooks/useSafeDispatch";
import { postCookingSessionRequest } from "../../actions";
import { useSelector } from "react-redux";
import { State } from "../../types";
import MenuItem from "./MenuItem";
import { selectDay } from "../../selectors";

interface Props {
  date: Date;
}

export default function MenuDay({ date }: Props) {
  const dispatch = useSafeDispatch();
  const recipes = useRecipes();
  const cookingSessions = useSelector((state: State) => selectDay(state, date));
  const [recipeId, setRecipeId] = useState("");

  return (
    <div>
      <h3>{convertDateToDayName(date)}</h3>
      <ul>
        {cookingSessions.map(({ id, recipe }) => (
          <MenuItem key={id} recipe={recipe} />
        ))}
      </ul>
      <form onSubmit={onRecipeSubmit}>
        <select onChange={onRecipeChange} value={recipeId}>
          <option>Выбрать рецепт</option>
          {recipes.map(({ id, title }) => (
            <option key={id} value={id}>
              {title}
            </option>
          ))}
        </select>
        &nbsp;
        <button>+</button>
      </form>
    </div>
  );

  function onRecipeChange(event: React.ChangeEvent<HTMLSelectElement>) {
    setRecipeId(event.target.value);
  }

  function onRecipeSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    dispatch(
      postCookingSessionRequest({
        recipeId,
        date,
      })
    );
    setRecipeId("");
  }
}
