import * as React from "react";
import { Link, RouteComponentProps } from "react-router-dom";
import { Formik, Form, Field } from "formik";
import { RecipeData } from "@spendcook/api";
import RecipeIngredients from "./RecipeIngredients";
import useSafeDispatch from "../../hooks/useSafeDispatch";
import { postRecipeRequest } from "../../actions";

const initialValues: RecipeData = {
  title: "",
  ingredients: [
    {
      ingredientId: "Рис",
      quantity: 0,
    },
  ],
};

export default function RecipeCreate({ history }: RouteComponentProps) {
  const dispatch = useSafeDispatch();
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={async (values) => {
        dispatch(postRecipeRequest(values));
        history.goBack();
      }}
    >
      {({ values }) => (
        <>
          <h2>{values.title || "Новый рецепт"}</h2>
          <div>
            <Form>
              <p>
                <label htmlFor="title">Название рецепта</label>
                <br />
                <Field name="title" id="title" type="text" />
              </p>
              <RecipeIngredients
                name="ingredients"
                values={values.ingredients}
              />
              <p>
                <button type="submit">Сохранить</button>
              </p>
            </Form>
            <p>
              <Link to="/recipes">{`<< Назад к меню`}</Link>
            </p>
          </div>
        </>
      )}
    </Formik>
  );
}
