import { Reorder } from "motion/react";
import InstructionElement from "./InstructionElement";
import type { Dispatch, SetStateAction } from "react";
import type { RecipeInstruction } from "../../types/recipe";


interface InstructionListProps {
  instructions: RecipeInstruction[];
  setInstructions: Dispatch<SetStateAction<RecipeInstruction[]>>;
}

export default function InstructionList({ instructions, setInstructions }: InstructionListProps) {
  const handleChange = (id: string, value: string) => {
    setInstructions(prev =>
      prev.map(instr =>
        instr.Id === id ? { ...instr, Content: value } : instr
      )
    );
  };

  const handleDelete = (id: string) => {
    setInstructions(prev =>
      prev.filter(instr => instr.Id !== id)
    );
  }

  return (
    <Reorder.Group
      axis="y"
      values={instructions}
      onReorder={setInstructions}
      className="flex flex-col gap-2 my-2"
    >
      {instructions.map((instruction, i) => (
        <InstructionElement
          key={instruction.Id}
          index={i}
          instruction={instruction}
          allowDelete={instructions.length > 1}
          onChange={handleChange}
          onDelete={handleDelete}
        />
      ))}
    </Reorder.Group>
  );
}
