<template>
  <div class="flex items-center gap-3">
    <div
      class="relative h-[84px] w-[84px] overflow-hidden rounded-lg border border-[var(--el-border-color)] bg-[var(--el-fill-color-light)]"
    >
      <ElImage
        v-if="modelValue"
        :src="modelValue"
        fit="cover"
        class="h-full w-full"
        :preview-src-list="[modelValue]"
        preview-teleported
      />
      <div
        v-else
        class="flex h-full w-full items-center justify-center text-xs text-[var(--el-text-color-secondary)]"
      >
        {{ t('tenant.manualCreate.action.noImage') }}
      </div>
    </div>

    <div class="flex flex-1 flex-col gap-2">
      <div class="flex items-center gap-2">
        <ElButton :loading="isUploading" type="primary" plain @click="openFileDialog">
          {{
            modelValue
              ? t('tenant.manualCreate.action.reupload')
              : t('tenant.manualCreate.action.upload')
          }}
        </ElButton>
        <ElButton
          v-if="modelValue"
          :disabled="isUploading"
          type="danger"
          plain
          @click="handleRemove"
        >
          {{ t('tenant.manualCreate.action.remove') }}
        </ElButton>
      </div>

      <div class="text-xs text-[var(--el-text-color-secondary)]">
        {{ uploadedFileName || t('tenant.manualCreate.action.tip') }}
      </div>
    </div>

    <input
      ref="fileInputRef"
      type="file"
      class="hidden"
      :accept="accept"
      @change="(e) => handleFileChange(e)"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { fetchUploadFile } from '@/api/files'

  defineOptions({ name: 'ImageUploadField' })

  const props = withDefaults(
    defineProps<{
      modelValue?: string
      uploadType?: Api.Files.UploadFileType
      accept?: string
    }>(),
    {
      modelValue: '',
      uploadType: 'other',
      accept: 'image/*'
    }
  )

  const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
  }>()

  const { t } = useI18n()

  const fileInputRef = ref<HTMLInputElement | null>(null)
  const isUploading = ref(false)
  const uploadedFileName = ref('')

  watch(
    () => props.modelValue,
    () => {
      // 1. 外部清空时同步清理文件名展示
      if (!props.modelValue) {
        uploadedFileName.value = ''
      }
    }
  )

  const openFileDialog = () => {
    // 1. 触发隐藏 input 选择文件
    fileInputRef.value?.click()
  }

  const handleFileChange = async (event: Event) => {
    // 1. 获取文件
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]
    if (!file) return

    // 2. 清空 input，支持重复选择同一文件
    target.value = ''

    // 3. 上传并写回 URL
    await uploadFile(file)
  }

  const uploadFile = async (file: File) => {
    // 1. 避免并发上传
    if (isUploading.value) return

    // 2. 调用上传接口
    isUploading.value = true
    try {
      const res = await fetchUploadFile(file, props.uploadType)
      const url = res.url || ''
      if (!url) {
        return
      }

      uploadedFileName.value = res.fileName || file.name
      emit('update:modelValue', url)
    } finally {
      isUploading.value = false
    }
  }

  const handleRemove = () => {
    // 1. 清空 URL（仅前端移除，不做后端删除）
    emit('update:modelValue', '')
  }
</script>
