import * as React from "react";
import { Recipe } from "@spendcook/api";
import { Link, RouteComponentProps } from "react-router-dom";
import { denormalize } from "normalizr";
import useSafeDispatch from "../../hooks/useSafeDispatch";
import { useCallback, useEffect } from "react";
import { fetchRecipesRequest } from "../../actions";
import { selectEntities } from "../../selectors";
import { recipeSchema } from "../../entities";
import { createSelector } from "reselect";
import { useSelector } from "react-redux";

export default function RecipeView({
  match,
}: RouteComponentProps<{ recipeId: string }>) {
  const { recipeId } = match.params;
  const recipe = useRecipe(recipeId);

  if (!recipe) {
    return null;
  }

  const { ingredients } = recipe;

  return (
    <>
      <h2>{recipeId}</h2>
      {ingredients.length > 0 ? (
        <table>
          {ingredients.map(({ quantity, ingredient }) => (
            <tr>
              <td>{ingredient.title}</td>
              <td>{quantity} гр.</td>
            </tr>
          ))}
        </table>
      ) : (
        <p>Ингредиентов нет</p>
      )}
      <p>
        <Link to="/recipes">{`<< Назад к меню`}</Link>
      </p>
    </>
  );
}

function useRecipe(recipeId: string) {
  const dispatch = useSafeDispatch();

  useEffect(() => {
    dispatch(fetchRecipesRequest());
  }, []);

  const selectRecipe = useCallback(
    createSelector([selectEntities], (entities) => {
      const recipe = entities.recipes[recipeId];

      return recipe
        ? (denormalize(recipe, recipeSchema, entities) as Recipe)
        : null;
    }),
    [recipeId]
  );

  return useSelector(selectRecipe);
}
