import React, { useState } from 'react';
import { addRecipe } from "../services/frontendApi.js";
import { useNavigate } from "react-router-dom";
import AddBulkIngredients from "../components/AddBulkIngredients.tsx"
import AddIngredientsForm from "../components/AddIngredientsForm.tsx"
import AddStepsForm from "../components/AddStepsForm.tsx"
import AddBulkSteps from "../components/AddBulkSteps.tsx"
import { type Ingredient, type Step } from "../types/Recipe";

function AddRecipe() {
  const [newRecipeId, setNewRecipeId] = useState<number | null>(null);
  const navigate = useNavigate();
  const [ingredients, setIngredients] = useState<Ingredient[]>([]);
  const [steps, setSteps] = useState<Step[]>([]);
  const [showBulkForm, setShowBulkForm] = useState(true);
  const [recipeName, setRecipeName] = useState("");
  const [recipeCuisine, setRecipeCuisine] = useState("");

  const addRecipeForm = async (event: React.FormEvent) => {
    event.preventDefault();
    const stepsHash = Object.fromEntries(
      steps.map(step => [step.idx, step.instructions])
    );
    if (recipeName && recipeCuisine && Object.keys(stepsHash).length > 0 && ingredients.length > 0) {
      const recipeData = {
        name: recipeName,
        cuisine: recipeCuisine,
        ingredients: ingredients,
        steps: stepsHash
      }
      console.log(recipeData)
      const data = await addRecipe(recipeData);
      setNewRecipeId(data.id);
    } else {
      alert('missing required data')
    }
  };

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

  return (
    <div className="add-recipe-outer">
      <form onSubmit={addRecipeForm} className="add-recipe-form">
        <input
          type="text"
          placeholder="name"
          className="recipe-name"
          value={recipeName}
          onChange={(e) => setRecipeName(e.target.value)}
        />
        <input
          type="text"
          placeholder="cuisine"
          className="recipe-cusine"
          value={recipeCuisine}
          onChange={(e) => setRecipeCuisine(e.target.value)}
        />
        <button type="submit" className="ar-button">
          submit
        </button>
      </form>
      <label>
        <input
          type="checkbox"
          checked={showBulkForm}
          onChange={(e) => setShowBulkForm(e.target.checked)}
        />
        Bulk Entry
      </label>
      <div>
        {showBulkForm ?
          <AddBulkIngredients ingredients={ingredients} onChange={setIngredients} /> :
          <AddIngredientsForm ingredients={ingredients} onSubmit={setIngredients} />
        }
      </div>
      <div>
        <ul>
          {ingredients.map((ing, index) => (
            <li key={index}>{`${ing.quantity} ${ing.unit} ${ing.name}`}</li>
          ))}
        </ul>
      </div>
      <div>
        {showBulkForm ?
          <AddBulkSteps steps={steps} onChange={setSteps} /> :
          <AddStepsForm steps={steps} onSubmit={setSteps} />
        }
      </div>
      <ul>
        {steps.map((step) => (
          <li key={step.idx}>{`${step.idx}. ${step.instructions}`}</li>
        ))}
      </ul>
    </div>
  )
}
export default AddRecipe
