<template>
  <div class="image-upload">
    <div class="upload-preview" v-if="modelValue">
      <img :src="modelValue" alt="预览" @error="imgError = true" />
      <div class="preview-actions">
        <button type="button" class="btn-icon" @click="$emit('update:modelValue', '')" title="移除">&#10005;</button>
      </div>
    </div>

    <div
      v-else
      class="upload-area"
      :class="{ dragging }"
      @click="triggerUpload"
      @dragover.prevent="dragging = true"
      @dragleave="dragging = false"
      @drop.prevent="handleDrop"
    >
      <div v-if="uploading" class="upload-loading">上传中...</div>
      <div v-else class="upload-placeholder">
        <span class="upload-icon">+</span>
        <span>点击或拖拽上传图片</span>
        <span class="upload-hint">JPG / PNG / WebP，最大 10MB</span>
      </div>
    </div>

    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileChange"
    />

    <p v-if="uploadError" class="upload-error">{{ uploadError }}</p>

    <!-- 或者直接填写路径 -->
    <div class="upload-manual">
      <input
        :value="modelValue"
        @input="$emit('update:modelValue', $event.target.value)"
        type="text"
        :placeholder="placeholder || '图片URL，可手动输入或上传'"
      />
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  modelValue: { type: String, default: '' },
  placeholder: { type: String, default: '' },
})

const emit = defineEmits(['update:modelValue'])

const { adminFetch } = useAdmin()
const fileInput = ref(null)
const uploading = ref(false)
const uploadError = ref('')
const dragging = ref(false)
const imgError = ref(false)

function triggerUpload() {
  fileInput.value?.click()
}

async function handleFileChange(e) {
  const file = e.target.files?.[0]
  if (file) await uploadFile(file)
  e.target.value = ''
}

function handleDrop(e) {
  dragging.value = false
  const file = e.dataTransfer?.files?.[0]
  if (file) uploadFile(file)
}

async function uploadFile(file) {
  if (file.size > 10 * 1024 * 1024) {
    uploadError.value = '文件过大，最大 10MB'
    return
  }

  uploading.value = true
  uploadError.value = ''

  try {
    const formData = new FormData()
    formData.append('file', file)

    const token = useState('admin_token')
    const result = await $fetch('/api/admin/upload', {
      method: 'POST',
      body: formData,
      headers: { Authorization: `Bearer ${token.value}` },
    })

    if (result.files?.length) {
      emit('update:modelValue', result.files[0].url)
      imgError.value = false
    }
  } catch (e) {
    uploadError.value = e.data?.message || '上传失败'
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.image-upload {
  margin-bottom: 4px;
}

.upload-preview {
  position: relative;
  width: 200px;
  height: 140px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #eee;
  margin-bottom: 8px;
}

.upload-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}

.btn-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: none;
  background: rgba(0,0,0,0.5);
  color: #fff;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-icon:hover {
  background: rgba(231,76,60,0.9);
}

.upload-area {
  width: 200px;
  height: 140px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 8px;
}

.upload-area:hover,
.upload-area.dragging {
  border-color: #3a7d44;
  background: #f8fdf9;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-icon {
  display: block;
  font-size: 28px;
  color: #ccc;
  margin-bottom: 4px;
}

.upload-placeholder span {
  display: block;
  font-size: 12px;
  line-height: 1.6;
}

.upload-hint {
  color: #bbb;
  font-size: 11px !important;
}

.upload-loading {
  color: #3a7d44;
  font-size: 13px;
}

.upload-manual input {
  width: 100%;
  max-width: 400px;
  padding: 6px 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  box-sizing: border-box;
}

.upload-manual input:focus {
  border-color: #3a7d44;
  outline: none;
}

.upload-error {
  color: #e74c3c;
  font-size: 12px;
  margin: 4px 0 0;
}
</style>
