<template>
  <dialog class="modal" :class="{ 'modal-open': open }">
    <div class="modal-box max-w-3xl">
      <h3 class="text-lg font-bold text-base-content">
        {{ modalTitle }}
      </h3>
      <p class="mt-1 text-sm text-base-content/70">
        {{ modalSubtitle }}
      </p>

      <div class="mt-4 rounded-xl border border-base-200 bg-base-100">
        <div v-if="loading" class="flex items-center gap-2 px-4 py-6 text-sm text-info">
          <span class="loading loading-spinner loading-sm" aria-hidden="true" />
          Chargement des éléments liés…
        </div>

        <div v-else-if="error" class="px-4 py-6 text-sm text-error">
          {{ error }}
        </div>

        <div
          v-else-if="items.length === 0"
          class="px-4 py-6 text-sm text-base-content/60"
        >
          Aucun élément lié à cette catégorie.
        </div>

        <ul v-else class="max-h-96 divide-y divide-base-200 overflow-y-auto">
          <li
            v-for="entry in items"
            :key="entry.id"
            class="px-2 py-1"
          >
            <div
              class="flex w-full items-center justify-between gap-2 rounded-lg px-2 py-2 hover:bg-base-200"
            >
              <div class="flex min-w-0 flex-col gap-0.5">
                <NuxtLink
                  :to="itemDetailPath(entry)"
                  class="font-medium hover:underline hover:text-primary transition-colors"
                  @click="emit('close')"
                >
                  {{ entry.name }}
                </NuxtLink>
                <span v-if="entry.reference" class="text-xs text-base-content/60">
                  Référence: {{ entry.reference }}
                </span>
              </div>
              <div class="shrink-0">
                <span v-if="entry.machineCount > 0" class="badge badge-ghost badge-sm">
                  {{ entry.machineCount }} machine{{ entry.machineCount > 1 ? 's' : '' }}
                </span>
                <span v-else class="text-xs text-base-content/30">Aucune machine</span>
              </div>
            </div>
          </li>
        </ul>
      </div>

      <div class="modal-action">
        <button type="button" class="btn" @click="emit('close')">
          Fermer
        </button>
      </div>
    </div>
  </dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useApi } from '~/composables/useApi'
import type { ModelCategory, ModelType } from '~/services/modelTypes'

type RelatedEntry = {
  id: string
  name: string
  reference?: string | null
  machineCount: number
}

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

const emit = defineEmits<{
  close: []
  'open-edit': [entry: RelatedEntry]
}>()

const { get } = useApi()

const loading = ref(false)
const error = ref<string | null>(null)
const items = ref<RelatedEntry[]>([])

const categoryLabels: Record<ModelCategory, { plural: string, singular: string }> = {
  COMPONENT: { plural: 'composants', singular: 'composant' },
  PIECE: { plural: 'pièces', singular: 'pièce' },
  PRODUCT: { plural: 'produits', singular: 'produit' },
}

const modalTitle = computed(() => {
  if (!props.modelType) return 'Éléments liés'
  return `Éléments liés à « ${props.modelType.name} »`
})

const modalSubtitle = computed(() => {
  if (!props.modelType) return ''
  const labels = categoryLabels[props.modelType.category] ?? categoryLabels.COMPONENT
  const count = items.value.length
  if (loading.value) return `Chargement des ${labels.plural}…`
  if (count === 0) return `Aucun ${labels.singular} lié.`
  if (count === 1) return `1 ${labels.singular} lié.`
  return `${count} ${labels.plural} liés.`
})

const itemDetailPath = (item: RelatedEntry) => {
  if (!props.modelType) return '#'
  const category = props.modelType.category
  if (category === 'COMPONENT') return `/component/${item.id}`
  if (category === 'PIECE') return `/piece/${item.id}`
  return `/product/${item.id}`
}

const loadRelatedItems = async (modelType: ModelType) => {
  loading.value = true
  error.value = null
  items.value = []

  try {
    const result = await get(`/model_types/${modelType.id}/related-items`)
    if (!result.success) {
      error.value = result.error ?? 'Impossible de charger les éléments liés.'
      return
    }
    if (Array.isArray(result.data)) {
      items.value = result.data as RelatedEntry[]
    }
  }
  catch {
    error.value = 'Impossible de charger les éléments liés.'
  }
  finally {
    loading.value = false
  }
}

watch(
  () => props.open,
  (isOpen) => {
    if (isOpen && props.modelType) {
      void loadRelatedItems(props.modelType)
    }
  },
)
</script>
