<script setup lang="ts">
import { AttachmentApiClient } from '@/api/attachment'
import { useAuthStore } from '@/stores/auth-store'
import { useRoute } from 'vue-router'
import AppButton from './AppButton.vue'
import { computed, useTemplateRef, type Ref } from 'vue'
import ModalWrapper from './ModalWrapper.vue'

interface AttachmentInfo {
  filename: string
  contentType: string
  size: number
  id?: number
  file?: File
}

const route = useRoute()
const api = new AttachmentApiClient(route)
const authStore = useAuthStore()
const props = defineProps<{ attachment: AttachmentInfo; disabled?: boolean }>()
defineEmits<{ deleted: [] }>()
const srcUrl: Ref<string | null> = computed(() => {
  if (props.attachment.file !== undefined) {
    return URL.createObjectURL(props.attachment.file)
  }
  if (props.attachment.id === undefined || authStore.state === null) {
    return null
  }
  return api.getAttachmentUrl(props.attachment.id, authStore.state.token)
})
const canPreviewAttachment = computed(() => {
  if (!srcUrl.value) return false
  const c = props.attachment.contentType
  return c.startsWith('image') || c === 'application/pdf'
})

const attachmentViewerModal = useTemplateRef('attachmentViewer')

function downloadFile() {
  if (!authStore.state) return
  api.downloadAttachment(props.attachment?.id ?? 0, authStore.state.token)
}
</script>
<template>
  <div class="attachment-row">
    <div style="display: flex; align-items: center; margin-left: 1rem">
      <div>
        <div>{{ attachment.filename }}</div>
        <div style="font-size: 0.75rem">{{ attachment.contentType }}</div>
      </div>
    </div>
    <div>
      <AppButton
        icon="eye"
        v-if="canPreviewAttachment"
        @click="attachmentViewerModal?.show()"
      ></AppButton>
      <AppButton
        icon="download"
        @click="downloadFile()"
        v-if="attachment.id !== undefined"
      />
      <AppButton
        v-if="!disabled"
        icon="trash"
        @click="$emit('deleted')"
      />
    </div>

    <ModalWrapper
      ref="attachmentViewer"
      v-if="canPreviewAttachment"
    >
      <div>
        <h3 style="margin-top: 0; margin-bottom: 0.25rem">{{ attachment.filename }}</h3>
        <embed
          :src="srcUrl ?? ''"
          :type="attachment.contentType"
          :class="{
            'attachment-embed-img': attachment.contentType.startsWith('image'),
            'attachment-embed-pdf': attachment.contentType === 'application/pdf',
          }"
        />
      </div>
    </ModalWrapper>
  </div>
</template>
<style lang="css">
.attachment-row {
  background-color: var(--bg);
  display: flex;
  justify-content: space-between;
  padding: 0.25rem;
  border-radius: 0.5rem;
  margin: 0.5rem 0;
}

.attachment-embed-img {
  width: 100%;
}

.attachment-embed-pdf {
  min-width: 500px;
  min-height: 500px;
}
</style>
