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

interface Step {
  step_number: number;
  instruction: string;
}

function AddRecipe() {
  const [newRecipeId, setNewRecipeId] = useState<number | null>(null);
  const navigate = useNavigate();
  const [ingredients, setIngredients] = useState<string[]>([]);
  const [steps, setSteps] = useState<Step[]>([]);
  const [showBulkForm, setShowBulkForm] = useState(true);
  const [recipeName, setRecipeName] = useState("");
  const [recipeCuisine, setRecipeCuisine] = useState("");
  const [author, setAuthor] = useState("");
  const [stars, setStars] = useState(0);
  const [prepMinutes, setPrepMinutes] = useState(5);
  const [cookMinutes, setCookMinutes] = useState(5);

  const addRecipeForm = async (event: React.FormEvent) => {
    event.preventDefault();
    const stepsHash = Object.fromEntries(
      steps.map(step => [step.step_number, step.instruction])
    );
    if (recipeName && recipeCuisine && Object.keys(stepsHash).length > 0 && ingredients.length > 0) {
      const recipeData = {
        name: recipeName,
        cuisine: recipeCuisine,
        author: author,
        prep_minutes: prepMinutes,
        cook_minutes: cookMinutes,
        stars: stars,
        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-card page-outer">
      <form onSubmit={addRecipeForm} className="add-recipe-form">
        <input
          type="text"
          placeholder="recipe name"
          className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full"
          value={recipeName}
          onChange={(e) => setRecipeName(e.target.value)}
        />
        <input
          type="text"
          placeholder="cuisine"
          className="recipe-cusine mb-4 p-2 border border-gray-300 rounded w-full"
          value={recipeCuisine}
          onChange={(e) => setRecipeCuisine(e.target.value)}
        />
        <input
          type="text"
          placeholder="author or source"
          className="recipe-cusine mb-4 p-2 border border-gray-300 rounded w-full"
          value={author}
          onChange={(e) => setAuthor(e.target.value)}
        />
        <div className="flex items-center justify-between mb-4">
          <div>
            <label htmlFor="prepTime" className="mr-2 font-bold">Prep Time:</label>
            <input
              type="number"
              placeholder="prep time in minutes"
              className="recipe-cusine p-2 border border-gray-300 rounded w-24"
              value={prepMinutes}
              onChange={(e) => setPrepMinutes(e.target.value)}
            />
            <span className="ml-2">minutes</span>
          </div>
          <div>
            <label htmlFor="cookTime" className="mr-2 font-bold">Cook Time:</label>
            <input
              type="text"
              placeholder="cook time in minutes"
              className="recipe-cusine p-2 border border-gray-300 rounded w-24"
              value={cookMinutes}
              onChange={(e) => setCookMinutes(e.target.value)}
            />
            <span className="ml-2">minutes</span>
          </div>
          <div>
            <StarRating rating={stars} onRatingChange={(newRating: number) => setStars(newRating)} />
          </div>
        </div>
        <label className="mb-4 flex items-center cursor-pointer">
          <div className="relative">
            <input
              type="checkbox"
              checked={showBulkForm}
              onChange={(e) => setShowBulkForm(e.target.checked)}
              className="sr-only"
            />
          </div>
        </label>
        <div>
          <AddBulkIngredients ingredients={ingredients} onChange={setIngredients} />
        </div>
        {/*<ul className="mb-4">
        {ingredients.map((ing, index) => (
          <li key={index} className="text-gray-700 flex items-start mb-2">
            <span>{ing}</span>
          </li>
        ))}
      </ul>*/}
        <div>
          <AddBulkSteps steps={steps} onChange={setSteps} />
        </div>
        {/*<ul className="mb-4">
        {steps.map((step) => (
          <li key={step.step_number} className="text-gray-700 flex items-start mb-2">
            <span>{`${step.step_number}. ${step.instruction}`}</span>
          </li>
        ))}
      </ul>*/}
        <button type="submit" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700">
          submit
        </button>
      </form>
    </div>
  )
}
export default AddRecipe
