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-card bg-amber-100 border border-amber-200 rounded-bl-lg rounded-br-lg p-6 md:p-8 lg:p-10 max-w-6xl mx-auto font-serif">
      <form onSubmit={addRecipeForm} className="add-recipe-form">
        <input
          type="text"
          placeholder="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)}
        />
        <button type="submit" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700">
          submit
        </button>
      </form>
      <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 className={`
            w-12 h-6 rounded-full shadow-sm transition-all duration-75 transform
            ${showBulkForm
              ? 'bg-amber-300 shadow-lg'
              : 'bg-amber-100 hover:bg-amber-200'
            }
          `}>
            <div className={`
              absolute top-0.5 left-0.5 w-5 h-5 rounded-full shadow-sm transition-all duration-100 transform
              ${showBulkForm
                ? 'translate-x-6 bg-white border-2 border-amber-400'
                : 'translate-x-0 bg-white border-2 border-amber-200'
              }
            `}></div>
          </div>
        </div>
        <span className="ml-3 text-amber-800 font-medium">Bulk Entry</span>
      </label>
      <div>
        {showBulkForm ?
          <AddBulkIngredients ingredients={ingredients} onChange={setIngredients} /> :
          <AddIngredientsForm ingredients={ingredients} onSubmit={setIngredients} />
        }
      </div>
      <ul className="mb-4">
        {ingredients.map((ing, index) => (
          <li key={index} className="text-gray-700 flex items-start mb-2">
            <span>{`${ing.quantity} ${ing.unit} ${ing.name}`}</span>
          </li>
        ))}
      </ul>
      <div>
        {showBulkForm ?
          <AddBulkSteps steps={steps} onChange={setSteps} /> :
          <AddStepsForm steps={steps} onSubmit={setSteps} />
        }
      </div>
      <ul className="mb-4">
        {steps.map((step) => (
          <li key={step.idx} className="text-gray-700 flex items-start mb-2">
            <span>{`${step.idx}. ${step.instructions}`}</span>
          </li>
        ))}
      </ul>
    </div>
  )
}
export default AddRecipe
