<template>
  <v-card>
    <v-card-title>Rename tag</v-card-title>
    <v-card-text>
      <template v-if="!collision">
        <v-text-field
          v-model="newName" label="New name" density="compact"
          autofocus @keydown.enter="submit"
        />
        <v-alert
          v-if="errorMsg" type="error" variant="tonal" density="compact"
          class="mt-2"
        >{{ errorMsg }}</v-alert>
      </template>

      <template v-else>
        <!-- A tag of this (kind, fandom) already has that name. Renaming onto it
             is a merge, not a fork — same resolution the Tags view offers. -->
        <v-alert type="warning" variant="tonal" density="compact" class="mb-3">
          A {{ tag.kind }} tag named “{{ collision.target.name }}” already exists.
        </v-alert>
        <p class="text-body-2">
          Merge “{{ tag.name }}” into “{{ collision.target.name }}”?
          {{ collision.source_image_count }} image
          association{{ collision.source_image_count === 1 ? '' : 's' }}
          will move over and this tag will be deleted{{
            collision.will_alias ? ' (its name kept as a tagger alias)' : '' }}.
        </p>
        <v-alert
          v-if="errorMsg" type="error" variant="tonal" density="compact"
          class="mt-3"
        >{{ errorMsg }}</v-alert>
      </template>
    </v-card-text>
    <v-card-actions>
      <v-spacer />
      <template v-if="!collision">
        <v-btn :disabled="busy" @click="$emit('cancel')">Cancel</v-btn>
        <v-btn
          color="primary" rounded="pill"
          :disabled="!newName.trim() || newName === tag.name"
          :loading="busy" @click="submit"
        >Rename</v-btn>
      </template>
      <template v-else>
        <v-btn :disabled="busy" @click="collision = null; errorMsg = null">
          Back
        </v-btn>
        <v-btn
          color="warning" variant="flat" rounded="pill"
          :loading="busy" @click="onMerge"
        >Merge</v-btn>
      </template>
    </v-card-actions>
  </v-card>
</template>

<script setup>
import { ref } from 'vue'
import { useApi } from '../../composables/useApi.js'

const props = defineProps({ tag: { type: Object, required: true } })
const emit = defineEmits(['renamed', 'cancel'])

const api = useApi()
const newName = ref(props.tag.name)
const errorMsg = ref(null)
const collision = ref(null)
const busy = ref(false)

async function submit() {
  if (!newName.value.trim() || newName.value === props.tag.name) return
  busy.value = true
  errorMsg.value = null
  try {
    const updated = await api.patch(`/api/tags/${props.tag.id}`, {
      body: { name: newName.value.trim() }
    })
    emit('renamed', updated)
  } catch (e) {
    // 409 → the new name collides with an existing tag of the same
    // (kind, fandom). Offer to merge into it rather than dead-ending.
    if (e.status === 409 && e.body && e.body.target) {
      collision.value = e.body
    } else {
      errorMsg.value = e.message
    }
  } finally {
    busy.value = false
  }
}

async function onMerge() {
  busy.value = true
  errorMsg.value = null
  try {
    await api.post(`/api/tags/${props.tag.id}/merge`, {
      body: { target_id: collision.value.target.id }
    })
    emit('renamed', { id: collision.value.target.id, name: collision.value.target.name })
  } catch (e) {
    errorMsg.value = e.message
  } finally {
    busy.value = false
  }
}
</script>
