<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="fileInput?.click()"
        >
          <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>
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleFileChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { t } from '@/shared/i18n'
import { uploadFileToJingrow, updateRecord, getRecordAttachments, deleteAttachment } from '@/shared/api/common'
import { useMessage } from 'naive-ui'
import { Icon } from '@iconify/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 fileInput = ref<HTMLInputElement | null>(null)

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)

async function handleFileChange(e: Event) {
  const el = e.target as HTMLInputElement
  const file = el.files?.[0]
  if (!file) return
  const fieldName = imageFieldName.value
  if (!fieldName || !props.entity || !props.id) return
  try {
    message.loading(t('Uploading...'), { duration: 0 })
    const result = await uploadFileToJingrow(file, props.entity, props.id, fieldName)
    message.destroyAll()
    if (result.success && result.file_url) {
      props.record[fieldName] = result.file_url
      await updateRecord(props.entity, props.id, { [fieldName]: result.file_url })
      emit('refresh')
    } else {
      message.error(result.error || t('Upload failed'))
    }
  } catch (error: any) {
    message.destroyAll()
    message.error(error.message || t('Upload failed'))
  } finally {
    el.value = ''
  }
}

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 attachments = await getRecordAttachments(props.entity, props.id)
      const file = attachments.data?.find((f: any) => f.file_url === url)
      if (file) {
        await deleteAttachment(file.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>
