import {useCallback, useEffect, useState} from 'react'
import PropTypes from 'prop-types'

const OnboardFeature = ({autoStart, steps, onEnd, onStart}) => {
    const [currentStep, setStep] = useState(-1)

    const start = useCallback(() => {
        setStep(0)
        onStart?.()
    }, [onStart])

    const end = useCallback(() => onEnd?.(), [onEnd])
    const back = useCallback(() => setStep(Math.max(currentStep - 1, 0)), [
        currentStep,
    ])
    const next = useCallback(
        () => setStep(Math.min(currentStep + 1, steps.length)),
        [currentStep, steps]
    )

    useEffect(() => {
        autoStart && start()
        return () => onEnd?.()
    }, [])

    // Effect handles changes in the current step – executes the step if
    // one exists.
    useEffect(() => {
        const startNextStep = steps[currentStep]
        startNextStep?.({
            onBack: back,
            onEnd: end,
            onNext: next,
            onStart: start,
        })
    }, [currentStep])

    return null
}

OnboardFeature.propTypes = {
    steps: PropTypes.arrayOf(PropTypes.func).isRequired,
    autoStart: PropTypes.bool,
    onEnd: PropTypes.func,
    onStart: PropTypes.func,
}

export default OnboardFeature
