import { Reorder } from "motion/react";
import type { RecipeIngredient, RecipeIngredientSection } from "../../types/recipe";
import IngredientItem from "./IngredientItem";
import type { RecipeValidationEntry } from "../../pages/Create";

interface IngredientListProps {
  classes: string;
  section: RecipeIngredientSection;
  ingredients: RecipeIngredient[];
  setSectionIngredients: (sectionId: string, ingredients: RecipeIngredient[]) => void;
  ingredientChangeHandler: (id: string, name: "Amount" | "Unit" | "Name", value: string) => void;
  removeIngredientHandler: (id: string) => void;
  validList: RecipeValidationEntry[];
  dirtyList: Record<string, boolean>;
  markDirty: (id: string) => void;
}

export default function IngredientList({ classes, section, ingredients, setSectionIngredients, ingredientChangeHandler, removeIngredientHandler, validList, dirtyList, markDirty }: IngredientListProps) {
  const sectionIngredients = ingredients.filter(x => x.SectionId === section.Id);

  const reorderHandler = (ingredients: RecipeIngredient[]) => {
    setSectionIngredients(section.Id, ingredients);
  }

  return (
    <Reorder.Group
      axis="y"
      values={ingredients}
      onReorder={reorderHandler}
      className="flex flex-col"
    >
      {sectionIngredients.map(ingredient =>
        <IngredientItem
          key={ingredient.Id}
          classes={classes}
          ingredient={ingredient}
          onChange={ingredientChangeHandler}
          removeIngredientHandler={removeIngredientHandler}
          allowDelete={sectionIngredients.length > 1}
          valid={validList.find(x => x.id === ingredient.Id)?.valid ?? true}
          dirty={dirtyList[ingredient.Id] ?? false}
          markDirty={markDirty}
        />
      )}
    </Reorder.Group>
  );
}
