<script setup lang="ts">
import { __ } from '@wordpress/i18n'
import { toRefs, ref } from 'vue'
import {
  LabelControl,
  Tooltip,
} from './index'
import {
  purifyHtml,
  getI18n,
} from '@/helper'

const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
})
const { params } = toRefs(props)

const arg = params.value
// The saved value is the attachment id; the URL is only ever used to show the picked
// image here and in the live preview, and is resolved server-side on page load.
const value = ref<string>(arg['default'] ?? '')
const imageUrl = ref<string>(arg['image_url'] ?? '')
const emit = defineEmits(['fieldData', 'previewRef'])
const inputValues = ref<any>([])
const previewRef = ref<any>([])

let frame: any = null

const emitValueChange = () => {
  inputValues.value[arg['id']] = value.value
  emit('fieldData', inputValues.value)

  // The live preview reads the URL off this control rather than off the saved value,
  // so it can render an image the merchant has picked but not saved yet.
  arg['image_url'] = imageUrl.value

  previewRef.value[arg['id']] = inputValues.value
  emit('previewRef', previewRef.value)
}

// The frame is cached across opens, and so is its selection. Without this the picker keeps
// highlighting whatever was chosen last — including an attachment already cleared via
// "Remove image" — so reopening it shows a selection the control no longer holds.
const syncFrameSelection = () => {
  const selection = frame?.state()?.get('selection')

  if (!selection) {
    return
  }

  selection.reset()

  if (!value.value) {
    return
  }

  const wp = (window as any).wp
  const attachment = wp?.media?.attachment?.(value.value)

  if (attachment) {
    attachment.fetch()
    selection.add([attachment])
  }
}

const openMediaLibrary = () => {
  const wp = (window as any).wp

  // wp.media is enqueued alongside the settings app; without it there is nothing to
  // open, and leaving the current selection alone is better than clearing it.
  if (!wp?.media) {
    return
  }

  if (frame) {
    syncFrameSelection()
    frame.open()
    return
  }

  frame = wp.media({
    title: getI18n('selectButtonIcon', __('Select Button Icon', 'saveto-wishlist-lite-for-woocommerce')),
    button: {
      text: getI18n('useThisImage', __('Use this image', 'saveto-wishlist-lite-for-woocommerce')),
    },
    // Whichever image types the site itself allows — a site that has enabled SVG uploads
    // can pick an SVG here, one that has not simply will not see any.
    library: { type: 'image' },
    multiple: false,
  })

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

    if (!attachment?.id) {
      return
    }

    value.value = String(attachment.id)
    imageUrl.value = attachment.url ?? ''
    emitValueChange()
  })

  frame.open()
}

const removeImage = () => {
  value.value = ''
  imageUrl.value = ''
  emitValueChange()
}
</script>

<template>
  <div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <LabelControl :params="arg" />
    </div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-3">
      <div
        class="stwlite-tw-w-16 stwlite-tw-h-16 stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-center stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-border-solid stwlite-tw-rounded-md stwlite-tw-bg-white stwlite-tw-overflow-hidden stwlite-tw-flex-shrink-0"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          alt=""
          class="stwlite-tw-max-w-full stwlite-tw-max-h-full stwlite-tw-object-contain"
        >
        <span v-else class="stwlite-tw-text-xs stwlite-tw-text-gray-400">
          {{ getI18n('noImage', __('No image', 'saveto-wishlist-lite-for-woocommerce')) }}
        </span>
      </div>
      <button
        type="button"
        class="stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-bg-blue-600 hover:stwlite-tw-bg-blue-700 stwlite-tw-text-white stwlite-tw-rounded-md stwlite-tw-cursor-pointer stwlite-tw-border-0"
        @click="openMediaLibrary"
      >
        {{ imageUrl
          ? getI18n('replaceImage', __('Replace image', 'saveto-wishlist-lite-for-woocommerce'))
          : getI18n('selectImage', __('Select image', 'saveto-wishlist-lite-for-woocommerce')) }}
      </button>
      <button
        v-if="imageUrl"
        type="button"
        class="stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-text-sm stwlite-tw-bg-gray-100 hover:stwlite-tw-bg-gray-200 stwlite-tw-text-gray-700 stwlite-tw-rounded-md stwlite-tw-cursor-pointer stwlite-tw-border-0"
        @click="removeImage"
      >
        {{ getI18n('removeImage', __('Remove image', 'saveto-wishlist-lite-for-woocommerce')) }}
      </button>
      <Tooltip :params="arg" />
    </div>
    <p v-if="arg['description'] !== 'undefined' && arg['description']" class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mt-2" v-html="purifyHtml(arg?.['description'] ?? '')" />
  </div>
</template>
