import React, { useState } from 'react';
import { addRecipe } from "../services/frontendApi.js";
import { useNavigate } from "react-router-dom";
import AddBulkIngredients from "../components/AddBulkIngredients.tsx"

function AddRecipe() {
  const [newRecipeId, setNewRecipeId] = useState<number | null>(null);
  const navigate = useNavigate();
  const [ingredients, setIngredients] = useState<{ quantity: number; unit: string; name: string }[]>([]);

  const addRecipeForm = async (event: React.FormEvent) => {
    event.preventDefault();
    const nameElement = document.getElementById('ar-name') as HTMLInputElement | null;
    const cuisineElement = document.getElementById('ar-cuisine') as HTMLInputElement | null;
    if (nameElement && cuisineElement) {
      const recipeData = {
        name: nameElement.value,
        cuisine: cuisineElement.value,
        ingredients: ingredients,
        steps: { 1: 'step 1', 2: 'step 2' }
      }
      console.log(recipeData)
      const data = await addRecipe(recipeData);
      setNewRecipeId(data.id);
    }
  };

  React.useEffect(() => {
    if (newRecipeId !== null) {
      navigate(`/recipe/${newRecipeId}`);
    }
  }, [newRecipeId, navigate]);

  return (
    <div className="add-recipe-outer">
      <form onSubmit={addRecipeForm} className="add-recipe-form">
        <input
          type="text"
          placeholder="name"
          className="ar-name"
          id="ar-name"
        />
        <input
          type="text"
          placeholder="cuisine"
          className="ar-cusine"
          id="ar-cuisine"
        />
        <button type="submit" className="ar-button">
          submit
        </button>
      </form>
      <div>
        <AddBulkIngredients onChange={setIngredients} />
      </div>
    </div>
  )
}
export default AddRecipe
