import {
    Flex,
} from '@wordpress/components';
import StepHeader from './step-header';
import StepBody from './step-body';
import arrayMove from '../utils/arrayMove';

const StepRepeater = ({
    steps,
    removeStep,
    updateSteps,
    questionLockPrefix,
}) => {
    const setStepField = (stepId, field, value) => {
        const updStepFields = steps.map((step, index) => {
            return step.id === stepId ? {...step, [field]: value} : step
        });

        updateSteps(updStepFields);
    };

    const moveStepUp = (index) => {
        if (
            steps.length > 1
            && index > 0
        ) {
            const stepsArr = [...steps];

            arrayMove(stepsArr, index, index - 1);
            stepsArr[0].collapsed = false;

            updateSteps(stepsArr);
        }
    };

    const moveStepDown = (index) => {
        if (
            steps.length > 1
            && index + 1 <= steps.length
        ) {
            const stepsArr = [...steps];

            arrayMove(stepsArr, index, index + 1);
            stepsArr[0].collapsed = false;

            updateSteps(stepsArr);
        }
    };

    return <Flex direction="column" gap={3} className="seoaic-steps-flex-wrapper">
        { steps.map((step, index) => {
            const questionLockName = questionLockPrefix + step.id;

            return <div className="seoaic-repeater-item">
                <StepHeader
                    steps={ steps }
                    currentStep={ step }
                    index={ index }
                    removeStep={ removeStep }
                    setStepField={ setStepField }
                    moveStepUp={ moveStepUp }
                    moveStepDown={ moveStepDown }
                    questionLockName={ questionLockName }
                />
                { step.collapsed
                ? ''
                : (
                    <StepBody
                        steps={ steps }
                        currentStep={ step }
                        currentIndex={ index }
                        setStepField={ setStepField }
                        updateSteps={ updateSteps }
                        questionLockName={ questionLockName }
                    />
                ) }
            </div>
        }) }
    </Flex>
};

export default StepRepeater;