import type { ApplicationFormDto, CreateFormElementDto, FormElementSectionDto } from '~~/.api-client'
import type { MaybeRefOrGetter } from 'vue'

export function useFormElementManagement(
  currentFormElementSection: MaybeRefOrGetter<FormElementSectionDto | undefined>,
  applicationFormId?: string
) {
  const { addFormElementToSection } = useApplicationForm()

  async function addInputFormToApplicationForm(position: number): Promise<ApplicationFormDto | undefined> {
    const section = toValue(currentFormElementSection)
    if (!section) return

    const { formElements } = section

    const inputFormElement: CreateFormElementDto = {
      title: 'Formular ergänzen',
      description: 'Bitte fügen Sie hier Ihre Ergänzungen ein.',
      options: [
        {
          value: '|||',
          label: '',
          processingPurpose: 'NONE',
          employeeDataCategory: 'NONE'
        }
      ],
      type: 'TITLE_BODY_TEXTFIELDS'
    }

    if (applicationFormId) {
      try {
        return await addFormElementToSection(applicationFormId, section.id, inputFormElement, position + 1)
      } catch (error) {
        console.error('Failed to add form element:', error)
        throw error
      }
    } else {
      // @ts-expect-error Add CreateFormElementDto to formElements array. ID will be generated by the backend.
      formElements.splice(position + 1, 0, inputFormElement)
      return undefined
    }
  }

  return {
    addInputFormToApplicationForm
  }
}
