<template>
  <v-card class="fc-danger-zone mt-8" variant="outlined">
    <CardHeading icon="mdi-alert-octagon" icon-color="error" title="Danger zone" />
    <v-card-text>
      <p class="text-body-2 fc-muted mb-4">
        Cascade-delete this artist and every image, source, post, and
        attachment associated with them. This cannot be undone.
        Recoverable only from an FC-3h backup.
      </p>
      <v-btn
        color="error" variant="flat" rounded="pill"
        prepend-icon="mdi-delete-forever"
        :loading="loading"
        @click="onClick"
      >Delete artist &amp; cascade</v-btn>

      <DestructiveConfirmModal
        v-model="modalOpen"
        action="delete"
        kind="artist"
        :run-id="artistId"
        tier="C"
        :projected-counts="projectedCounts"
        :description="modalDescription"
        @confirm="onConfirm"
      />
    </v-card-text>
  </v-card>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

import DestructiveConfirmModal from '../modal/DestructiveConfirmModal.vue'
import { useAdminStore } from '../../stores/admin.js'
import CardHeading from '../common/CardHeading.vue'

const props = defineProps({
  slug: { type: String, required: true },
  artistId: { type: Number, required: true },
  artistName: { type: String, required: true },
})

const router = useRouter()
const store = useAdminStore()
const loading = ref(false)
const modalOpen = ref(false)
const projected = ref(null)

const projectedCounts = computed(() => projected.value?.projected || null)

// `posts` is named here, not left to the counts grid below it: an artist whose
// posts are body-only previews as `images: 0`, and a summary line that says
// only "0 images" reads as "this artist is empty" while the apply destroys
// every captured post body (#3067). Attachments stay in the grid — the grid
// renders every key, so this line carries only what changes the read.
const modalDescription = computed(() => {
  const p = projectedCounts.value
  return p
    ? `Artist “${props.artistName}” — ${p.images} images, `
      + `${p.posts} posts, ${p.sources} sources, `
      + `${Math.round(p.bytes_on_disk / 1_048_576)} MiB on disk`
    : ''
})

async function onClick() {
  loading.value = true
  try {
    projected.value = await store.projectArtistCascade(props.slug)
    modalOpen.value = true
  } finally {
    loading.value = false
  }
}

async function onConfirm(token) {
  loading.value = true
  try {
    const result = await store.dispatchArtistCascade(props.slug, token)
    const taskId = result.task_id
    router.push('/artists')
    if (taskId) {
      store.pollTaskUntilDone(taskId).catch(() => {})
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.fc-danger-zone {
  border-color: rgb(var(--v-theme-error));
  border-radius: 8px;
}
</style>
