<template>
  <div @click="openMediaDialog" class="loyalty-suite-form__preview" :class="{ 'loyalty-suite-form__preview_empty': !previewUrl }">
    <div class="loyalty-suite-form__preview-container">
      <img v-if="previewUrl" :src="previewUrl" class="loyalty-suite-form__preview-img" />
      <q-btn v-if="previewUrl" icon="close" color="negative" @click.stop="removeImage" class="loyalty-suite-form__preview-remove" />
      <q-icon v-else name="file_upload" class="loyalty-suite-form__preview-icon" />
      <span v-if="previewName" class="loyalty-suite-form__preview-name">{{ previewName }}</span>
      <span v-else class="loyalty-suite-form__preview-label">{{ $t('fileUpload') }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

export default defineComponent({
  name: 'WpMediaUploader',
  props: {
    modelValue: Number
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const { t } = useI18n();
    const previewUrl = ref<string | null>(null);
    const previewName = ref<string | null>(null);

    const wp = (window as any).wp;

    const loadAttachment = (id: number) => {
      if (!wp || !wp.media || !id) return;
      const attachment = wp.media.attachment(id);
      attachment.fetch().then(() => {
        const data = attachment.toJSON();
        previewUrl.value = data.url;
        previewName.value = data.filename;
      });
    };

    watch(
      () => props.modelValue,
      (val) => {
        if (typeof val === 'number') {
          loadAttachment(val);
        } else {
          previewUrl.value = null;
          previewName.value = null;
        }
      },
      { immediate: true }
    );

    const openMediaDialog = () => {
      if (!wp || !wp.media) {
        alert(t('mediaUnavailable'));
        return;
      }

      const frame = wp.media({
        title: t('selectImage'),
        multiple: false,
        library: { type: 'image' },
        button: { text: t('useImage') }
      });

      if (typeof props.modelValue === 'number') {
        const attachment = wp.media.attachment(props.modelValue);
        attachment.fetch();
        frame.on('open', () => {
          frame.state().get('selection').add(attachment);
        });
      }

      frame.on('select', () => {
        const attachment = frame.state().get('selection').first().toJSON();

        if (attachment.type !== 'image') {
          alert(t('iconFormat'));
          return;
        }

        emit('update:modelValue', attachment.id);
        previewUrl.value = attachment.url;
        previewName.value = attachment.filename;
      });

      frame.open();
    };

    const removeImage = () => {
      emit('update:modelValue', null);
      previewUrl.value = null;
      previewName.value = null;
    };

    return {
      openMediaDialog,
      previewUrl,
      previewName,
      removeImage
    };
  }
});
</script>
