<template>
  <div class="media-section" v-if="hasImageField">
    <div class="image-grid">
      <div class="image-card" :class="{ 'has-image': hasImages }">
        <img
          v-if="hasImages"
          :src="imageUrl"
          :alt="imageFieldName"
          @click="$emit('open-gallery', imageUrl)"
        />
        <div
          v-else-if="canEdit"
          class="upload-placeholder"
          @click="openUploadDialog"
        >
          <Icon icon="tabler:upload" class="upload-icon" />
        </div>
        <div v-if="canEdit && hasImages" class="image-overlay">
          <button class="delete-btn" :title="t('Remove')" @click.stop="removeImage">
            <Icon icon="tabler:x" />
          </button>
        </div>
      </div>
    </div>
    
    <!-- 上传对话框 -->
    <FileUploadDialog 
      v-model:show="showUploadDialog"
      :pagetype="entity"
      :pagename="id"
      :pagefield="imageFieldName"
      @uploaded="onUploaded"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { t } from '@/shared/i18n'
import { updateRecord, getRecords, deleteAttachment } from '@/shared/api/common'
import { useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import FileUploadDialog from '@/views/pagetype/file/FileUploadDialog.vue'

const props = defineProps<{
  metaFields: any[]
  record: Record<string, any>
  pageMeta: any
  canEdit?: boolean
  entity?: string
  id?: string
}>()

const emit = defineEmits<{
  'open-gallery': [url: string]
  'refresh': []
}>()

const message = useMessage()
const showUploadDialog = ref(false)

const imageFieldName = computed(() => props.pageMeta?.image_field)

const hasImageField = computed(() => {
  const name = imageFieldName.value
  if (!name?.trim()) return false
  return props.metaFields.some(f => f.fieldname === name)
})

const imageUrl = computed(() => {
  const name = imageFieldName.value
  if (!name) return ''
  return String(props.record[name] || '').trim()
})

const hasImages = computed(() => !!imageUrl.value)

function openUploadDialog() {
  if (!props.canEdit) return
  showUploadDialog.value = true
}

async function onUploaded() {
  showUploadDialog.value = false
  
  const fieldName = imageFieldName.value
  if (!fieldName) return
  
  try {
    // 获取最新上传的图片
    const res = await getRecords('File', [
      ['attached_to_pagetype', '=', props.entity || ''],
      ['attached_to_name', '=', props.id || ''],
    ], ['file_url'], 'creation desc', 0, 1)
    
    if (res.success && res.data?.length) {
      const latestFile = res.data[0]
      props.record[fieldName] = latestFile.file_url
      await updateRecord(props.entity || '', props.id || '', { [fieldName]: latestFile.file_url })
      emit('refresh')
      message.success(t('Image uploaded successfully'))
    }
  } catch (error: any) {
    message.error(error.message || t('Upload failed'))
  }
}

async function removeImage() {
  const fieldName = imageFieldName.value
  if (!fieldName || !props.entity || !props.id) return
  const url = imageUrl.value
  try {
    message.loading(t('Removing...'), { duration: 0 })
    if (url) {
      const res = await getRecords('File', [
        ['attached_to_pagetype', '=', props.entity],
        ['attached_to_name', '=', props.id],
        ['file_url', '=', url],
      ], ['name'])
      if (res.success && res.data?.length) {
        for (const f of res.data) {
          await deleteAttachment(f.name)
        }
      }
    }
    props.record[fieldName] = ''
    await updateRecord(props.entity || '', props.id || '', { [fieldName]: '' })
    message.destroyAll()
    emit('refresh')
  } catch (error: any) {
    message.destroyAll()
    message.error(error.message || t('Remove failed'))
  }
}
</script>

<style scoped>
.media-section {
  margin-bottom: 24px;
}

.media-section:last-child {
  margin-bottom: 0;
}

.image-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-card {
  position: relative;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.image-card img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  object-fit: contain;
  display: block;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.image-card img:hover {
  transform: scale(1.02);
}

.upload-placeholder {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 8px;
  border: 1.5px dashed #d1d5db;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.15s ease, background 0.15s ease;
  color: #9ca3af;
}

.upload-placeholder:hover {
  border-color: #6b7280;
  background: #f9fafb;
  color: #6b7280;
}

.upload-icon {
  font-size: 24px;
  opacity: 0;
  transition: opacity 0.15s ease;
}

.upload-placeholder:hover .upload-icon {
  opacity: 1;
}

.image-overlay {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
  z-index: 10;
}

.image-card:hover .image-overlay {
  opacity: 1;
}

.delete-btn {
  width: 20px;
  height: 20px;
  border: none;
  border-radius: 50%;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.delete-btn:hover {
  background: rgba(220, 38, 38, 0.95);
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}
</style>
