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

export function useFormImport() {
  const { getLabel } = useLabels()
  const { request } = useApiClient()
  const isImporting = ref(false)
  const importError = ref<string | null>(null)

  /**
   * Import forms from JSON file
   * @param file - JSON file containing form data
   * @returns Array of imported forms with { id, name } or false on error
   */
  const importForms = async (file: File): Promise<Array<{ id: number; name: string }> | false> => {
    isImporting.value = true
    importError.value = null

    try {
      // Read file content
      const fileContent = await readFileAsText(file)
      const importData = JSON.parse(fileContent)

      // Validate import data structure
      if (!importData.forms || !Array.isArray(importData.forms)) {
        importError.value = getLabel('invalid_import_file')
        return false
      }

      // Send import request
      const { data, error } = await request('forms/import', {
        method: 'POST',
        data: {
          importData,
        },
      })

      if (error) {
        importError.value = error || getLabel('failed_to_import_forms')
        return false
      }

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

      if (response && response.success) {
        // Return the imported forms data
        return response.data || false
      } else {
        importError.value = response?.message || getLabel('failed_to_import_forms')
        return false
      }
    } catch (error) {
      console.error('Import error:', error)
      if (error instanceof SyntaxError) {
        importError.value = getLabel('invalid_import_file')
      } else {
        importError.value = getLabel('failed_to_import_forms')
      }
      return false
    } finally {
      isImporting.value = false
    }
  }

  /**
   * Read file as text
   */
  const readFileAsText = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        if (e.target?.result) {
          resolve(e.target.result as string)
        } else {
          reject(new Error('Failed to read file'))
        }
      }
      reader.onerror = () => reject(new Error('Failed to read file'))
      reader.readAsText(file)
    })
  }

  return {
    isImporting,
    importError,
    importForms,
  }
}
