<script setup lang="ts">
import { ref, watch } from 'vue'
import { presignDownload } from '@/core/api'
import { cn } from '@/lib/utils'
import { useLocalTranslation } from '@/lib/composables/useLocalTranslation'
import ImagePreviewDialog from './ImagePreviewDialog.vue'

const props = defineProps<{
  fileId?: string
  imageUrl?: string
  class?: string
  enablePreview?: boolean
  onClick?: () => void
}>()

const { i18n } = useLocalTranslation()
const imageUrl = ref<string | null>(props.imageUrl || null)
const loading = ref(!props.imageUrl && !!props.fileId)
const error = ref(false)
const isPreviewOpen = ref(false)

watch(
  () => [props.fileId, props.imageUrl] as const,
  async ([fileId, propUrl]) => {
    if (propUrl) {
      imageUrl.value = propUrl
      loading.value = false
      return
    }
    if (fileId) {
      try {
        loading.value = true
        error.value = false
        const response = await presignDownload(fileId, i18n.language as 'ar' | 'en')
        imageUrl.value = response.downloadUrl
      } catch {
        error.value = true
      } finally {
        loading.value = false
      }
    }
  },
  { immediate: true }
)

function handleImageClick() {
  if (props.onClick) {
    props.onClick()
  } else if (props.enablePreview !== false && imageUrl.value) {
    isPreviewOpen.value = true
  }
}
</script>

<template>
  <div
    v-if="loading"
    :class="cn(
      'babylai:flex babylai:items-center babylai:justify-center babylai:bg-black-white-100 babylai:rounded-lg babylai:w-16 babylai:h-16',
      props.class
    )"
  >
    <div class="babylai:animate-pulse babylai:text-xs babylai:text-black-white-500">...</div>
  </div>

  <div
    v-else-if="error || !imageUrl"
    :class="cn(
      'babylai:flex babylai:items-center babylai:justify-center babylai:bg-black-white-100 babylai:rounded-lg babylai:w-16 babylai:h-16 babylai:border babylai:border-black-white-200',
      props.class
    )"
  >
    <div class="babylai:text-xs babylai:text-black-white-500">!</div>
  </div>

  <template v-else>
    <img
      :src="imageUrl"
      alt="Attachment"
      :class="cn(
        'babylai:w-16 babylai:h-16 babylai:object-cover babylai:rounded-lg babylai:border babylai:border-black-white-200 babylai:max-w-[50px]',
        (enablePreview !== false || onClick) && 'babylai:cursor-pointer babylai:hover:opacity-80 babylai:transition-opacity',
        props.class
      )"
      :role="enablePreview !== false || onClick ? 'button' : undefined"
      :aria-label="enablePreview !== false || onClick ? 'Click to preview image' : undefined"
      @error="error = true"
      @click="handleImageClick"
    />
    <ImagePreviewDialog
      v-if="enablePreview !== false && !onClick"
      :image-urls="[imageUrl]"
      :initial-index="0"
      :is-open="isPreviewOpen"
      alt="Attachment preview"
      @close="isPreviewOpen = false"
    />
  </template>
</template>
