// @ts-nocheck

import { useState, useCallback, Children } from 'react'

export interface UseWizardProps {
  currentStepIndex?: number
  isPrevDisabled?: boolean
  isNextDisabled?: boolean
  isFirstStep?: boolean
  isLastStep?: boolean
  isLoading?: boolean
  goToPrev?(): void
  goToNext?(): void
  handlePrev?(): void
  handleNext?(values: any): void
}

const useWizard = (
  activeStepIndex: number,
  steps: React.ReactNode,
  onSubmit: any
) => {
  const [currentStep, setCurrentStep] = useState(activeStepIndex)
  const [isLoading, setIsLoading] = useState(false)
  const total: number = Children.map(steps, (step) => (step ? step : [])).length
  const isPrevDisabled: boolean = currentStep === 0
  const isFirstStep: boolean = currentStep === 0
  const isLastStep: boolean = currentStep >= total - 1
  const goToPrev = useCallback(
    () => setCurrentStep(Math.max(0, currentStep - 1)),
    [setCurrentStep, currentStep]
  )
  const goToNext = useCallback(
    () => setCurrentStep(Math.min(currentStep + 1, total - 1)),
    [setCurrentStep, currentStep, total]
  )

  const { beforePrev, beforeNext } = steps[currentStep].props

  const handlePrev = useCallback(async () => {
    let isValid = true
    setIsLoading(true)
    if (beforePrev) {
      try {
        await beforePrev()
      } catch (error) {
        isValid = false
      }
    } else {
      isValid = true
    }
    setIsLoading(false)
    if (isValid) {
      goToPrev()
    }
  }, [goToPrev, currentStep, beforePrev])

  const handleNext = useCallback(
    async (values) => {
      let isValid = false
      setIsLoading(true)
      if (beforeNext) {
        try {
          const [err] = await beforeNext(values)
          isValid = err ? false : true
        } catch (error) {
          isValid = false
        }
      } else {
        isValid = true
      }
      if (isValid) {
        if (isLastStep) {
          setIsLoading(true)
          await onSubmit(values)
          setIsLoading(false)
        } else {
          goToNext()
        }
      }
      setIsLoading(false)
    },
    [goToNext, currentStep, beforeNext, isLastStep, onSubmit]
  )

  return {
    currentStepIndex: currentStep,
    isPrevDisabled,
    isFirstStep,
    isLastStep,
    isLoading,
    goToPrev,
    goToNext,
    handlePrev,
    handleNext
  }
}

export { useWizard }
