import { ref } from 'vue'
import { useApiClient } from '@/composables/useApiClient'
import { useLabels } from '@/composables/useLabels'

export function useFormExport() {
  const { getLabel } = useLabels()
  const { request } = useApiClient()
  const isExporting = ref(false)
  const exportError = ref<string | null>(null)

  /**
   * Export single or multiple forms
   * @param formIds - Array of form IDs to export
   */
  const exportForms = async (formIds: number[], formName?: string) => {
    isExporting.value = true
    exportError.value = null

    try {
      const { data, error } = await request('forms/export', {
        method: 'POST',
        data: {
          formIds,
        },
      })

      if (error) {
        exportError.value = error || getLabel('failed_to_export_forms')
        return false
      }

      // API returns: { message: "OK", data: { success: true, data: {...}, message: "..." } }
      const response = data?.data

      if (response && response.success) {
        // Create download link
        const exportData = response.data
        const dataStr = JSON.stringify(exportData, null, 2)
        const dataBlob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(dataBlob)

        // Create download link
        const link = document.createElement('a')
        link.href = url

        // Generate filename
        const safeName = formName
          ? formName
              .trim()
              .replace(/[^a-z0-9_-]/gi, '-')
              .replace(/-+/g, '-')
              .replace(/^-|-$/g, '')
          : 'ivyforms-export'
        link.download =
          formIds.length === 1 ? `${safeName}.json` : `ivyforms-export-${formIds.length}-forms.json`

        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)

        return true
      } else {
        exportError.value = response?.message || getLabel('failed_to_export_forms')
        return false
      }
    } catch (error) {
      console.error('Export error:', error)
      exportError.value = getLabel('failed_to_export_forms')
      return false
    } finally {
      isExporting.value = false
    }
  }

  return {
    isExporting,
    exportError,
    exportForms,
  }
}
