import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "./AdminPage.css";

function AdminPage() {
  const navigate = useNavigate();
  const [recipes, setRecipes] = useState([]);
  const [newRecipe, setNewRecipe] = useState({
    name: "",
    ingredients: "",
    instructions: "",
  });
  const [editingRecipeId, setEditingRecipeId] = useState(null);

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (!token) {
      navigate("/login");
    }
  }, [navigate]);

  //загр рецептов
  useEffect(() => {
    const storedRecipes = localStorage.getItem("recipes");
    if (storedRecipes) {
      setRecipes(JSON.parse(storedRecipes));
    }
  }, []);

  //сохр рецептов при изменении
  useEffect(() => {
    localStorage.setItem("recipes", JSON.stringify(recipes));
  }, [recipes]);

  const handleInputChange = (e, recipeId = null) => {
    const { name, value } = e.target;

    if (recipeId) {
      setRecipes((prevRecipes) =>
        prevRecipes.map((recipe) =>
          recipe.id === recipeId ? { ...recipe, [name]: value } : recipe
        )
      );
    } else {
      setNewRecipe((prevState) => ({
        ...prevState,
        [name]: value,
      }));
    }
  };

  const addRecipe = (e) => {
    e.preventDefault();
    if (newRecipe.name && newRecipe.ingredients && newRecipe.instructions) {
      const newRecipeWithId = { ...newRecipe, id: Date.now() }; 
      setRecipes([...recipes, newRecipeWithId]);
      setNewRecipe({ name: "", ingredients: "", instructions: "" });
    } else {
      alert("Пожалуйста, заполните все поля.");
    }
  };

  const deleteRecipe = (recipeId) => {
    if (window.confirm("Вы уверены, что хотите удалить этот рецепт?")) {
      const updatedRecipes = recipes.filter((recipe) => recipe.id !== recipeId);
      setRecipes(updatedRecipes);
    }
  };

  const startEditing = (recipeId) => {
    setEditingRecipeId(recipeId);
  };

  const stopEditing = () => {
    setEditingRecipeId(null);
  };

  const saveRecipe = (recipeId) => {
    const recipeIndex = recipes.findIndex(recipe => recipe.id === recipeId);

    if (recipeIndex !== -1) {
        const updatedRecipes = [...recipes];
        updatedRecipes[recipeIndex] = {
            ...updatedRecipes[recipeIndex],
            name: updatedRecipes[recipeIndex].name, 
            ingredients: updatedRecipes[recipeIndex].ingredients, 
            instructions: updatedRecipes[recipeIndex].instructions 
        };
        setRecipes(updatedRecipes);
        localStorage.setItem("recipes", JSON.stringify(updatedRecipes));
    }
    stopEditing();
  };

  return (
    <div className="admin-page">
      <h1>Админ-панель</h1>

      <div className="recipe-form">
        <h2>Добавить рецепт</h2>
        <form onSubmit={addRecipe}>
          <label>Название:</label>
          <input
            type="text"
            name="name"
            value={newRecipe.name}
            onChange={handleInputChange}
          />

          <label>Ингредиенты:</label>
          <textarea
            name="ingredients"
            value={newRecipe.ingredients}
            onChange={handleInputChange}
          />

          <label>Инструкции:</label>
          <textarea
            name="instructions"
            value={newRecipe.instructions}
            onChange={handleInputChange}
          />

          <button type="submit">Добавить</button>
        </form>
      </div>

      <div className="recipe-table">
        <h2>Список рецептов</h2>
        <table>
          <thead>
            <tr>
              <th>Название</th>
              <th>Ингредиенты</th>
              <th>Инструкции</th>
              <th>Действия</th>
            </tr>
          </thead>
          <tbody>
            {recipes.map((recipe) => (
              <tr key={recipe.id}>
                <td>
                  {editingRecipeId === recipe.id ? (
                    <input
                      type="text"
                      name="name"
                      value={recipe.name}
                      onChange={(e) => handleInputChange(e, recipe.id)}
                    />
                  ) : (
                    recipe.name
                  )}
                </td>
                <td>
                  {editingRecipeId === recipe.id ? (
                    <textarea
                      name="ingredients"
                      value={recipe.ingredients}
                      onChange={(e) => handleInputChange(e, recipe.id)}
                    />
                  ) : (
                    recipe.ingredients
                  )}
                </td>
                <td>
                  {editingRecipeId === recipe.id ? (
                    <textarea
                      name="instructions"
                      value={recipe.instructions}
                      onChange={(e) => handleInputChange(e, recipe.id)}
                    />
                  ) : (
                    recipe.instructions
                  )}
                </td>
                <td>
                  {editingRecipeId === recipe.id ? (
                    <>
                      <button onClick={() => saveRecipe(recipe.id)}>
                        Сохранить
                      </button>
                      <button onClick={stopEditing}>Отменить</button>
                    </>
                  ) : (
                    <>
                      <button onClick={() => startEditing(recipe.id)}>
                        Редактировать
                      </button>
                      <button onClick={() => deleteRecipe(recipe.id)}>
                        Удалить
                      </button>
                    </>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default AdminPage;