<script setup lang="ts">
/**
 * 视频上传组件
 * 支持拖拽/点击上传视频文件，复用附件上传接口
 */
import { ref, computed } from 'vue'
import { useToast } from '../../composables/useToast'
import { API_BASE, authFetch, parseApiResponse } from '../../services/api'

const props = withDefaults(defineProps<{
  modelValue?: string
  categoryId?: number
  disabled?: boolean
}>(), {
  disabled: false,
})

const emit = defineEmits<{ 'update:modelValue': [value: string] }>()

const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const error = ref('')
const isDragging = ref(false)
const toast = useToast()

const videoUrl = computed({
  get: () => props.modelValue || '',
  set: (val: string) => emit('update:modelValue', val),
})

const triggerFileInput = () => {
  if (props.disabled || uploading.value) return
  fileInput.value?.click()
}

/** 上传单个视频文件 */
const uploadFile = async (file: File) => {
  if (!file.type.startsWith('video/')) {
    error.value = '请选择视频文件'
    toast.error('请选择视频文件')
    return
  }
  uploading.value = true
  error.value = ''
  try {
    const formData = new FormData()
    formData.append('file', file)
    if (props.categoryId) formData.append('categoryId', props.categoryId.toString())
    const result = await parseApiResponse<{ fileUrl: string }>(
      await authFetch(`${API_BASE}/admin/attachments/upload`, { method: 'POST', headers: {}, body: formData })
    )
    videoUrl.value = result.fileUrl
    toast.success('视频上传成功')
  } catch (err) {
    error.value = err instanceof Error ? err.message : '上传失败'
    toast.error(error.value)
  } finally {
    uploading.value = false
  }
}

const handleFileSelect = (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]
  if (file) uploadFile(file)
  input.value = ''
}

const handleDrop = (e: DragEvent) => {
  e.preventDefault()
  isDragging.value = false
  if (props.disabled) return
  const file = e.dataTransfer?.files?.[0]
  if (file) uploadFile(file)
}

const removeVideo = () => {
  videoUrl.value = ''
}
</script>

<template>
  <div class="video-upload">
    <div
      v-if="!videoUrl"
      class="upload-area border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors"
      :class="isDragging ? 'border-art-accent bg-art-accent/5' : 'border-white/20 hover:border-art-accent/50'"
      @click="triggerFileInput"
      @dragover.prevent="isDragging = true"
      @dragleave.prevent="isDragging = false"
      @drop.prevent="handleDrop"
    >
      <input ref="fileInput" type="file" accept="video/*" class="hidden" :disabled="disabled" @change="handleFileSelect" />
      <div class="space-y-3">
        <div class="w-12 h-12 mx-auto flex items-center justify-center text-art-muted">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
        </div>
        <p class="text-sm text-art-muted">点击或拖拽视频到此处上传</p>
        <p class="text-xs text-art-muted/50">支持 MP4、WebM 等格式</p>
      </div>
    </div>

    <div v-else class="relative group rounded-lg overflow-hidden bg-black/40 border border-white/10">
      <video :src="videoUrl" class="w-full max-h-64 object-contain" controls preload="metadata" />
      <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
        <button type="button" class="px-4 py-2 bg-red-500/80 text-white rounded text-sm" @click="removeVideo">删除</button>
        <button type="button" class="px-4 py-2 bg-art-accent text-black rounded text-sm" @click="triggerFileInput">更换</button>
      </div>
    </div>

    <div v-if="uploading" class="mt-3 text-center text-art-accent text-sm flex items-center justify-center gap-2">
      <div class="animate-spin rounded-full h-4 w-4 border-t-2 border-art-accent"></div>
      上传中...
    </div>
    <div v-if="error" class="mt-2 text-red-400 text-sm">{{ error }}</div>
  </div>
</template>
