<template>
  <ImagePreview
    :url="image?.image ?? null"
    class="tw-inline-flex tw-h-64 tw-max-w-full tw-min-w-[300px] tw-bg-gray-700 tw-rounded"
    v-bind="attrs"
  >
    <div
      class="tw-absolute tw-bottom-0 tw-left-0 tw-right-0 tw-p-2 tw-flex tw-items-center tw-justify-between tw-bg-black/75 tw-text-white"
    >
      <button
        type="button"
        class="btn btn-secondary btn-sm tw-inline-flex tw-items-center"
        @click="showPicker = true"
      >
        <icon-carbon-image-search class="tw-mr-1 tw-w-6 tw-h-6" />
        {{ t('imagePicker.chooseAnImage') }}
      </button>
      <button
        v-if="modelValue"
        type="button"
        class="btn text-white btn-sm tw-inline-flex tw-items-center"
        @click="localImageId = null"
      >
        {{ t('imagePicker.reset') }}
      </button>
    </div>
  </ImagePreview>
  <ImagePickerDialog
    v-if="showPicker"
    v-model="localImageId"
    :is-open="true"
    @show="showPicker = $event"
  />
</template>

<script lang="ts" setup>
import { computed, ref, useAttrs } from 'vue'
import { useI18n } from '@/i18n'
import { useImage } from '@/stores/images'
import { useUpdatableState } from '@/util'
import ImagePickerDialog from './ImagePickerDialog.vue'
import ImagePreview from './ImagePreview.vue'

const props = defineProps<{
  modelValue: number | null
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', imageId: number | null): void
}>()
const attrs = useAttrs()
const { t } = useI18n()
const showPicker = ref(false)
const localImageId = useUpdatableState<number | null>(
  computed(() => props.modelValue),
  (value) => emit('update:modelValue', value),
)
const image = useImage(computed(() => props.modelValue))
</script>

<script lang="ts">
export default {
  inheritAttrs: false,
  compatConfig: {
    MODE: 3,
  },
}
</script>