import { useState } from "react";
import type { RecipeIngredient, RecipeIngredientSection, RecipeIngredientUnit } from "../types/recipe";

export function useIngredients() {
  // State values
  const [sections, setSections] = useState<RecipeIngredientSection[]>([
    { Id: "initial-section", Name: "Unnamed group" },
  ]);

  const [ingredients, setIngredients] = useState<RecipeIngredient[]>([
    { Id: crypto.randomUUID(), SectionId: "initial-section", Name: "", Amount: 0, Unit: "" as RecipeIngredientUnit },
  ]);

  // Section handlers
  const sectionChange = (id: string, name: string) => {
    setSections(prev => prev.map(s => (s.Id === id ? { ...s, Name: name } : s)));
  };

  const setSectionIngredients = (sectionId: string, list: RecipeIngredient[]) => {
    const sorted = [
      ...list.filter(x => x.SectionId === sectionId),
      ...ingredients.filter(x => x.SectionId !== sectionId),
    ].sort((a, b) => a.SectionId.localeCompare(b.SectionId));
    setIngredients(sorted);
  };

  const addSection = (index: number) => {
    const id = crypto.randomUUID();
    setSections(prev => [
      ...prev.slice(0, index + 1),
      { Id: id, Name: "Unnamed group" },
      ...prev.slice(index + 1),
    ]);
    setIngredients(prev => [
      ...prev,
      { Id: crypto.randomUUID(), SectionId: id, Amount: 0, Name: "", Unit: "" as RecipeIngredientUnit },
    ]);
  };

  const removeSection = (id: string) => {
    setSections(prev => prev.filter(sec => sec.Id !== id));
    setIngredients(prev => prev.filter(ing => ing.SectionId !== id));
  };

  // Ingredient handlers
  const ingredientChange = (id: string, name: "Amount" | "Unit" | "Name", value: string) => {
    setIngredients(prev =>
      prev.map(ing =>
        ing.Id === id
          ? { ...ing, [name]: name === "Amount" ? Number(value) : value }
          : ing
      )
    );
  };

  const addIngredient = (sectionId: string) => {
    setIngredients(prev =>
      [...prev, {
        Id: crypto.randomUUID(),
        SectionId: sectionId,
        Amount: 0,
        Name: "",
        Unit: "" as RecipeIngredientUnit,
      }].sort((a, b) => a.SectionId.localeCompare(b.SectionId))
    );
  };

  const removeIngredient = (id: string) => {
    setIngredients(prev => prev.filter(ing => ing.Id !== id));
  };

  return {
    sections,
    ingredients,
    setIngredients,
    setSections,
    sectionChange,
    ingredientChange,
    setSectionIngredients,
    addIngredient,
    removeIngredient,
    addSection,
    removeSection,
  };
}
