import type {IngredientModel} from "../../models/IngredientModel"
import type {IngredientGroupModel} from "../../models/IngredientGroupModel"
import Button from "../basics/Button"
import {Plus} from "lucide-react"
import {ButtonType} from "../basics/BasicButtonDefinitions"
import IngredientGroupEditorListItem from "./IngredientGroupEditorListItem.tsx";

type IngredientGroupListEditorProps = {
    ingredientGroupList: IngredientGroupModel[]
    onChange: (ingredientGroupList: IngredientGroupModel[]) => void
}

/**
 * Editor for ingredient groups
 * @param ingredientGroupList List model containing ingredient groups
 * @param onChange Method to call on change
 */
export function IngredientGroupListEditor({ingredientGroupList, onChange}: IngredientGroupListEditorProps) {
    /**
     * Update a member of the ingredient group list
     * @param index Index of the ingredient group to change
     * @param field Field name to change
     * @param value New value
     */
    const handleUpdate = (index: number, field: keyof IngredientGroupModel, value: string | IngredientModel[]) => {
        const updated = ingredientGroupList.map((ingGrp, i) =>
            i === index ? {...ingGrp, [field]: value} : ingGrp
        )
        onChange(updated)
    }

    /**
     * Add a new ingredient group to the list
     */
    const handleAdd = () => {
        onChange([...ingredientGroupList, {title: "", ingredientList: []}])
    }

    /**
     * Remove an ingredient group from the list
     * @param index Index of the group to remove
     */
    const handleRemove = (index: number) => {
        onChange(ingredientGroupList.filter((_, i) => i !== index))
    }
    return (
        <div>
            <h2>Zutaten</h2>
            <div>
                {ingredientGroupList.map((ingGrp, index) => (
                    <IngredientGroupEditorListItem
                        index={index}
                        key={index}
                        ingredientGroupModel={ingGrp}
                        handleUpdate={handleUpdate}
                        handleRemove={handleRemove}
                    />
                ))}
            </div>
            <Button
                onClick={handleAdd}
                icon={Plus}
                text={"Gruppe hinzufügen"}
                buttonType={ButtonType.PrimaryButton}
            />
        </div>
    )
}