import { ref } from 'vue'
import { uploadFile } from '@/api/file'
import { getUploadUrl } from '@/utils/file'
import type { Attachment } from '@/types/flow'

export function useFileUpload() {
  const attachmentList = ref<any[]>([])
  const previousAttachments = ref<Attachment[]>([])
  const previewVisible = ref(false)
  const previewUrl = ref('')

  async function handleUpload(options: any) {
    try {
      const res = await uploadFile(options.file)
      options.onSuccess?.(res)
    } catch (e: any) {
      options.onError?.(e)
    }
  }

  async function loadPreviousAttachments(loader?: () => Promise<Attachment[]>) {
    if (!loader) {
      previousAttachments.value = []
      return
    }
    try {
      previousAttachments.value = await loader()
    } catch {
      previousAttachments.value = []
    }
  }

  function openPreview(url: string) {
    if (!url) return
    previewUrl.value = url
    previewVisible.value = true
  }

  function handleFilePreview(file: any) {
    const url = getUploadUrl(file)
    if (url) openPreview(url)
  }

  function resetFileUpload() {
    attachmentList.value = []
    previousAttachments.value = []
    previewUrl.value = ''
    previewVisible.value = false
  }

  return {
    attachmentList,
    previousAttachments,
    previewVisible,
    previewUrl,
    handleUpload,
    loadPreviousAttachments,
    openPreview,
    handleFilePreview,
    resetFileUpload,
  }
}
