import type { FormElementSectionDto } from '~~/.api-client'
import type { StepperItem } from '@nuxt/ui'
import type { MaybeRefOrGetter } from 'vue'

interface Stepper {
  hasPrev: boolean
  hasNext: boolean
  next: () => void
  prev: () => void
}

export function useFormStepper(
  formElementSections: MaybeRefOrGetter<FormElementSectionDto[] | undefined>,
  options?: {
    onNavigate?: (direction: 'forward' | 'backward', newIndex: number) => void | Promise<void>
  }
) {
  const stepper = useTemplateRef<Stepper>('stepper')
  const activeStepperItemIndex = ref<number>(0)

  const sections = computed(() => toValue(formElementSections) ?? [])

  const stepperItems = computed(() => {
    const items: StepperItem[] = []
    sections.value.forEach((section: FormElementSectionDto) => {
      items.push({
        title: section.shortTitle,
        description: section.description
      })
    })
    return items
  })

  const currentFormElementSection = computed<FormElementSectionDto | undefined>(
    () => sections.value[activeStepperItemIndex.value]
  )

  async function navigateStepper(direction: 'forward' | 'backward') {
    if (direction === 'forward') {
      stepper.value?.next()
    } else {
      stepper.value?.prev()
    }

    if (options?.onNavigate) {
      await options.onNavigate(direction, activeStepperItemIndex.value)
    }
  }

  return {
    stepper,
    activeStepperItemIndex,
    stepperItems,
    currentFormElementSection,
    navigateStepper
  }
}
