<template>
  <FormGroup :errors="[error]">
    <div>
      <button
        type="button"
        class="btn btn-default tw-w-full tw-justify-center"
        @click="confirmDeleteShow"
      >
        <Loading v-if="isProcessing" class="tw-h-2" />
        {{ t('show.editor.deletion.label') }}
      </button>
      <ADescription>{{ t('show.editor.deletion.description') }}</ADescription>
    </div>
  </FormGroup>

  <ConfirmDeletion v-slot="{ resolve }">
    <AConfirmDialog
      :title="t('show.editor.deletion.label')"
      :confirm-label="t('show.editor.deletion.confirm.confirmLabel', { show: sanitizedShowName })"
      :prompt-value="show.slug"
      :prompt-label="t('show.editor.deletion.confirm.prompt', { challenge: show.slug })"
      class="tw-max-w-xl"
      @confirm="resolve(true)"
      @cancel="resolve(false)"
    >
      <SafeHTML
        as="p"
        :html="t('show.editor.deletion.confirm.text', { show: sanitizedShowName })"
        sanitize-preset="inline-noninteractive"
      />
    </AConfirmDialog>
  </ConfirmDeletion>
</template>
<script setup lang="ts">
import { createTemplatePromise } from '@vueuse/core'
import { computed } from 'vue'
import { sanitizeHTML, useAsyncFunction } from '@/util'
import { Show } from '@/types'
import { useI18n } from '@/i18n'
import { useShowStore } from '@/stores'

import FormGroup from '@/components/generic/FormGroup.vue'
import Loading from '@/components/generic/Loading.vue'
import SafeHTML from '@/components/generic/SafeHTML'
import AConfirmDialog from '@/components/generic/AConfirmDialog.vue'
import ADescription from '@/components/generic/ADescription.vue'
import { useRouter } from 'vue-router'

const props = defineProps<{
  show: Show
}>()

const { t } = useI18n()
const router = useRouter()
const showStore = useShowStore()

const ConfirmDeletion = createTemplatePromise<boolean>()
const sanitizedShowName = computed(() => sanitizeHTML(props.show.name))

const {
  fn: deleteShow,
  isProcessing,
  error,
} = useAsyncFunction(() => showStore.remove(props.show.id))

async function confirmDeleteShow() {
  if (await ConfirmDeletion.start()) {
    try {
      await deleteShow()
      await router.push({ name: 'shows' })
    } catch (e) {
      // error handling is done above
    }
  }
}
</script>