import { ref, computed } from 'vue'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import type { SyncMode, UploadedZip } from './types'

export function usePushForm() {
  const snackbar = useSnackbar()

  const sourcePath = ref('')
  const targetPath = ref('')
  const syncMode = ref<SyncMode>('incremental')

  const isDragging = ref(false)
  const uploadedZip = ref<UploadedZip | null>(null)
  const zipUploading = ref(false)
  const syncModeDesc = computed(() => {
    switch (syncMode.value) {
      case 'incremental':
        return '仅传输新增或修改的文件'
      case 'full':
        return '使目标目录与源目录完全一致，会删除不存在于源的文件'
      case 'checksum':
        return '通过文件内容校验和判断是否需要传输'
      default:
        return ''
    }
  })

  function effectiveSourcePath(): string {
    return uploadedZip.value?.sourcePath || sourcePath.value
  }

  function validateForm(selectedCount: number): boolean {
    if (!effectiveSourcePath()) {
      snackbar('请选择源路径或上传 ZIP 文件', 'warning')
      return false
    }
    if (!targetPath.value.trim()) {
      snackbar('请填写目标路径', 'warning')
      return false
    }
    if (selectedCount === 0) {
      snackbar('请选择至少一台服务器', 'warning')
      return false
    }
    return true
  }

  async function handleZipDrop(e: DragEvent) {
    isDragging.value = false
    const file = e.dataTransfer?.files[0]
    if (file?.name.endsWith('.zip')) await uploadZip(file)
  }

  function handleZipSelect(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) uploadZip(file)
  }

  async function uploadZip(file: File) {
    zipUploading.value = true
    try {
      const form = new FormData()
      form.append('file', file)
      const res = await http.upload<{ source_path: string; file_count: number; size: number }>(
        '/sync/upload-zip',
        form,
      )
      uploadedZip.value = {
        name: file.name,
        sourcePath: res.source_path,
        fileCount: res.file_count,
        size: res.size,
      }
      snackbar('ZIP 上传成功')
    } catch (e: unknown) {
      snackbar(e instanceof Error ? e.message : '上传失败', 'error')
    } finally {
      zipUploading.value = false
    }
  }

  function clearZipUpload() {
    uploadedZip.value = null
  }

  return {
    sourcePath,
    targetPath,
    syncMode,
    syncModeDesc,
    isDragging,
    uploadedZip,
    zipUploading,
    effectiveSourcePath,
    validateForm,
    handleZipDrop,
    handleZipSelect,
    clearZipUpload,
  }
}
