<template>
  <dialog class="modal" :class="{ 'modal-open': open }">
    <div class="modal-box max-w-2xl">
      <h3 class="text-lg font-bold text-base-content">
        Convertir la catégorie
      </h3>

      <!-- Loading state -->
      <div v-if="checking" class="mt-4 flex items-center gap-2 text-sm text-info">
        <span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
        Vérification de la conversion…
      </div>

      <!-- Error state -->
      <div v-else-if="checkError" class="mt-4 text-sm text-error">
        {{ checkError }}
      </div>

      <!-- Blocked state -->
      <template v-else-if="checkResult && !checkResult.canConvert">
        <p class="mt-3 text-sm text-base-content/70">
          La conversion de « {{ modelType?.name }} » est impossible pour les raisons suivantes :
        </p>
        <ul class="mt-3 space-y-1">
          <li
            v-for="(blocker, i) in checkResult.blockers"
            :key="i"
            class="flex items-start gap-2 rounded-lg border border-error/20 bg-error/5 px-3 py-2 text-sm text-error"
          >
            <IconLucideCircleX class="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
            {{ blocker }}
          </li>
        </ul>
      </template>

      <!-- Eligible state -->
      <template v-else-if="checkResult && checkResult.canConvert">
        <div class="mt-3 rounded-lg border border-warning/20 bg-warning/5 px-4 py-3">
          <p class="text-sm font-medium text-warning">
            {{ directionLabel }}
          </p>
          <p class="mt-1 text-sm text-base-content/70">
            {{ checkResult.itemCount }} élément(s) seront convertis. Cette opération est irréversible.
          </p>
        </div>

        <div
          v-if="checkResult.names.length > 0"
          class="mt-3 rounded-xl border border-base-200 bg-base-100"
        >
          <p class="px-4 pt-3 text-sm font-medium text-base-content/70">
            Éléments concernés :
          </p>
          <ul class="max-h-48 divide-y divide-base-200 overflow-y-auto px-4 pb-3">
            <li
              v-for="(name, i) in checkResult.names"
              :key="i"
              class="py-1.5 text-sm text-base-content"
            >
              {{ name }}
            </li>
          </ul>
        </div>

        <div v-if="convertError" class="mt-3 text-sm text-error">
          {{ convertError }}
        </div>
      </template>

      <div class="modal-action">
        <button
          type="button"
          class="btn"
          :disabled="converting"
          @click="emit('close')"
        >
          Fermer
        </button>
        <button
          v-if="checkResult?.canConvert"
          type="button"
          class="btn btn-warning"
          :disabled="converting"
          @click="doConvert"
        >
          <span v-if="converting" class="loading loading-spinner loading-sm" aria-hidden="true"></span>
          Convertir
        </button>
      </div>
    </div>
  </dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import IconLucideCircleX from '~icons/lucide/circle-x';
import {
  checkConversion,
  convertCategory,
  type ConversionCheck,
  type ModelType,
} from '~/services/modelTypes';

const props = defineProps<{
  open: boolean;
  modelType: ModelType | null;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'converted'): void;
}>();

const checking = ref(false);
const checkError = ref<string | null>(null);
const checkResult = ref<ConversionCheck | null>(null);
const converting = ref(false);
const convertError = ref<string | null>(null);

const directionLabel = computed(() => {
  if (!checkResult.value) return '';
  return checkResult.value.direction === 'piece_to_component'
    ? 'Conversion : Catégorie de pièce → Catégorie de composant'
    : 'Conversion : Catégorie de composant → Catégorie de pièce';
});

watch(
  () => props.open,
  async (isOpen) => {
    if (!isOpen || !props.modelType) {
      return;
    }

    checking.value = true;
    checkError.value = null;
    checkResult.value = null;
    convertError.value = null;

    try {
      checkResult.value = await checkConversion(props.modelType.id);
    } catch (err: any) {
      checkError.value =
        err?.data?.message || err?.message || 'Erreur lors de la vérification.';
    } finally {
      checking.value = false;
    }
  },
);

const doConvert = async () => {
  if (!props.modelType) return;

  converting.value = true;
  convertError.value = null;

  try {
    const result = await convertCategory(props.modelType.id);

    if (!result.success) {
      convertError.value = result.error || 'La conversion a échoué.';
      return;
    }

    emit('converted');
  } catch (err: any) {
    convertError.value =
      err?.data?.message || err?.message || 'Erreur lors de la conversion.';
  } finally {
    converting.value = false;
  }
};
</script>
