<script lang="ts" setup>
import type { FactorRouter, FactorUser } from '@factor/api'
import { useService, vue } from '@factor/api'
import ElInput from './ElInput.vue'
import ElButton from './ElButton.vue'

const { factorRouter, factorUser } = useService<{
  factorRouter: FactorRouter
  factorUser: FactorUser
}>()

const sending = vue.ref<string | boolean>(false)
const sent = vue.ref(false)

const organization = vue.computed(() => factorUser.activeOrganization.value)
/**
 * Delete organization after confirmation
 */
async function maybeDeleteOrganization(): Promise<void> {
  const organizationId = organization.value?.organizationId
  if (!organizationId)
    return
  const confirmed = confirm(
    'Are you sure? Deleting this organization will delete its assets and data permanently.',
  )

  if (confirmed) {
    sending.value = 'delete'
    await factorUser.requests.ManageOrganization.request({
      _action: 'delete',
      organizationId,
    })

    await factorRouter.goto('organizationIndex')
    sent.value = true
    sending.value = false
  }
}
</script>

<template>
  <ElInput
    :label="`Permanently Delete Organization (You are an ${factorUser.activeRelation.value?.memberAccess})`"
    sub-label="Permanently delete this organization and its data."
  >
    <div class="my-2 rounded-md">
      <ElButton
        :loading="sending === 'delete'"
        btn="default"
        size="sm"
        @click="maybeDeleteOrganization()"
      >
        Permanently Delete Organization: "{{ organization?.organizationName }}"
      </ElButton>
    </div>
  </ElInput>
</template>
