import {Plus} from "lucide-react";
import type {InstructionStepModel} from "../../models/InstructionStepModel";
import Button from "../basics/Button";
import {ButtonType} from "../basics/BasicButtonDefinitions";
import {instructionStepListEditorMethods} from "./InstructionStepListEditorMethods.ts";
import {InstructionStepEditorMobileListItem} from "./InstructionStepEditorMobileListItem.tsx";

type InstructionStepListEditorMobileProps = {
    instructionStepList: InstructionStepModel[];
    onChange: (steps: InstructionStepModel[]) => void;
};

/**
 * Mobile editor using Up/Down buttons for reordering
 * @param instructionStepList List instruction step models
 * @param onChange Method to call on any change to the list
 */
export function InstructionStepListMobileEditor({
                                                    instructionStepList,
                                                    onChange,
                                                }: InstructionStepListEditorMobileProps) {
    /* Import methods for handling update of instruction steps as well as adding and removing steps.
     * Those methods are shared by all versions of the instruction step editor, e.g., mobile and desktop.
     */
    const {handleUpdate, handleAdd, handleRemove} = instructionStepListEditorMethods(
        instructionStepList,
        onChange
    );

    /**
     * Move an instruction step either up or down in list.
     * @param index Current index of the step to move
     * @param direction Direction to move the step in. Either "up" or "down".
     */
    const moveStep = (index: number, direction: "up" | "down") => {
        const newIndex = direction === "up" ? index - 1 : index + 1;
        if (newIndex < 0 || newIndex >= instructionStepList.length) return;
        const newList = [...instructionStepList];
        const [moved] = newList.splice(index, 1);
        newList.splice(newIndex, 0, moved);
        onChange(newList);
    };

    return (
        <div>
            <h2 className="mb-2">Zubereitung</h2>

            {/* Instruction list */}
            <div className="flex flex-col gap-3">
                {instructionStepList.map((step, index) => (
                    <InstructionStepEditorMobileListItem
                        index={index}
                        stepModel={step}
                        onMove={moveStep}
                        onUpdate={handleUpdate}
                        onRemove={handleRemove}
                        isFirst={index === 0}
                        isLast={index === instructionStepList.length - 1}
                    />
                ))}

                {/* Button for adding an additional instruction step */}
                <Button
                    onClick={handleAdd}
                    icon={Plus}
                    text="Schritt hinzufügen"
                    buttonType={ButtonType.PrimaryButton}
                    className="mt-4"
                />
            </div>
        </div>
    );
}
