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


interface InstructionListProps {
  instructions: RecipeInstruction[];
  setInstructions: Dispatch<SetStateAction<RecipeInstruction[]>>;
  validList: RecipeValidationEntry[];
  dirtyList: Record<string, boolean>;
  markDirty: (id: string) => void;
}

export default function InstructionList({ instructions, setInstructions, validList, dirtyList, markDirty }: 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}
          valid={validList.find(x => x.id === instruction.Id)?.valid ?? true}
          dirty={dirtyList[instruction.Id] ?? false}
          markDirty={markDirty}
        />
      ))}
    </Reorder.Group>
  );
}
