import { computed, ref } from "vue"

import { buildOseCardCouponUrl, buildOseCardPreviewUrl } from "@/module/ose-card/service/card-url"

export function useOseCardEditSupport({ data, store }) {
  const imageDrawerVisible = ref(false)
  const couponDrawerVisible = ref(false)
  const couponType = ref("")
  const couponForm = ref({
    coupon_code: "",
    affiliate_code: "",
  })

  const cardCodeUrl = computed(() =>
    buildOseCardCouponUrl(
      data.landing_page,
      data.card_code,
      couponType.value,
      couponForm.value.coupon_code,
      couponForm.value.affiliate_code
    )
  )

  const openImageDrawer = () => {
    imageDrawerVisible.value = true
  }

  const openCouponDrawer = () => {
    couponDrawerVisible.value = true
  }

  const previewCard = () => {
    window.open(buildOseCardPreviewUrl(data.landing_page, data.card_code))
  }

  // Keep upload and image selection side effects close to the drawer state,
  // so the main edit page can focus on the card form itself.
  const uploadImage = async (event) => {
    const form = new FormData()
    form.append("file", event.file)
    await store.dispatch("ose_card_store/uploadImages", form)
  }

  const selectImage = (imageUrl) => {
    data.card_img_url = imageUrl
  }

  return {
    imageDrawerVisible,
    couponDrawerVisible,
    couponType,
    couponForm,
    cardCodeUrl,
    openImageDrawer,
    openCouponDrawer,
    previewCard,
    uploadImage,
    selectImage,
  }
}
