import { useLabels } from '@/composables/useLabels'
import { useFormImport } from '@/composables/useFormImport'
import IvyMessage from '@/views/_components/message/ivyMessage'

interface ImportedFormResult {
  id: number | string
  name: string
}

interface ValidImportedFormResult extends ImportedFormResult {
  id: number
}

interface HandleImportedFormsOptions {
  showSuccessMessage?: boolean
  showErrorMessage?: boolean
  successMessage?: string
  onAfterSuccessfulImport?: (
    importedFormIds: number[],
    importedForms: ValidImportedFormResult[],
  ) => void | Promise<void>
  onSingleFormImported?: (
    formId: number,
    importedForm: ValidImportedFormResult,
    importedFormIds: number[],
    importedForms: ValidImportedFormResult[],
  ) => void | Promise<void>
  onMultipleFormsImported?: (
    importedFormIds: number[],
    importedForms: ValidImportedFormResult[],
  ) => void | Promise<void>
}

export function useImportedFormsFlow() {
  const { getLabel } = useLabels()
  const { importForms, isImporting, importError } = useFormImport()

  const getValidImportedForms = (
    importedForms: ImportedFormResult[],
  ): ValidImportedFormResult[] => {
    return importedForms.reduce<ValidImportedFormResult[]>((forms, form) => {
      const formId = Number(form.id)

      if (Number.isInteger(formId) && formId > 0) {
        forms.push({
          ...form,
          id: formId,
        })
      }

      return forms
    }, [])
  }

  const getImportedFormIds = (importedForms: ImportedFormResult[]): number[] => {
    return getValidImportedForms(importedForms).map((form) => form.id)
  }

  const showImportError = (message?: string) => {
    IvyMessage({
      message: message || importError.value || getLabel('failed_to_import_forms'),
      type: 'error',
    })
  }

  const handleImportedForms = async (
    file: File,
    options: HandleImportedFormsOptions = {},
  ): Promise<number[]> => {
    const {
      showSuccessMessage = false,
      showErrorMessage = true,
      successMessage = getLabel('forms_imported_successfully'),
      onAfterSuccessfulImport,
      onSingleFormImported,
      onMultipleFormsImported,
    } = options

    const importedForms = await importForms(file)

    if (!importedForms || !Array.isArray(importedForms) || importedForms.length === 0) {
      if (showErrorMessage) {
        showImportError()
      }
      return []
    }

    const validImportedForms = getValidImportedForms(importedForms)
    const importedFormIds = validImportedForms.map((form) => form.id)

    if (importedFormIds.length === 0) {
      if (showErrorMessage) {
        showImportError()
      }
      return []
    }

    if (showSuccessMessage) {
      IvyMessage({
        message: successMessage,
        type: 'success',
      })
    }

    await onAfterSuccessfulImport?.(importedFormIds, validImportedForms)

    if (importedFormIds.length === 1) {
      await onSingleFormImported?.(
        importedFormIds[0],
        validImportedForms[0],
        importedFormIds,
        validImportedForms,
      )
    } else {
      await onMultipleFormsImported?.(importedFormIds, validImportedForms)
    }

    return importedFormIds
  }

  return {
    isImporting,
    importError,
    handleImportedForms,
    getImportedFormIds,
    getValidImportedForms,
  }
}
