<template>
  <div class="space-y-1">
    <SearchSelect
      :model-value="modelValue ?? undefined"
      :options="composantOptions"
      :loading="loading"
      :placeholder="placeholder"
      :empty-text="emptyText"
      size="sm"
      option-value="id"
      option-label="name"
      :disabled="disabled"
      @update:modelValue="updateValue"
    >
      <template #option-description="{ option }">
        <span class="text-xs text-base-content/60">
          {{ formatDescription(option) }}
        </span>
      </template>
    </SearchSelect>
    <p v-if="helperText" class="text-xs text-base-content/60">
      {{ helperText }}
    </p>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, watch } from 'vue'
import SearchSelect from '~/components/common/SearchSelect.vue'
import { useComposants } from '~/composables/useComposants'

const props = withDefaults(
  defineProps<{
    modelValue?: string | null
    placeholder?: string
    emptyText?: string
    helperText?: string
    disabled?: boolean
    typeComposantId?: string | null
  }>(),
  {
    modelValue: '',
    placeholder: 'Sélectionner un composant…',
    emptyText: 'Aucun composant disponible',
    helperText: '',
    disabled: false,
    typeComposantId: null,
  },
)

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | null): void
}>()

const { composants, loading, loadComposants } = useComposants()

const composantOptions = computed(() => {
  const baseOptions = Array.isArray(composants.value) ? composants.value : []
  if (!props.typeComposantId) {
    return baseOptions
  }

  const allowedTypeId = String(props.typeComposantId)
  return baseOptions.filter((composant: any) => {
    const typeId =
      composant?.typeComposantId ||
      composant?.typeComposant?.id ||
      null
    return typeId ? String(typeId) === allowedTypeId : false
  })
})

onMounted(() => {
  if (composantOptions.value.length === 0) {
    loadComposants({ itemsPerPage: 200 }).catch((error: unknown) => {
      console.error('Erreur lors du chargement des composants:', error)
    })
  }
})

watch(
  () => props.modelValue,
  (value) => {
    if (typeof value === 'string' && value) {
      const exists = composantOptions.value.some((c: any) => c.id === value)
      if (!exists && !loading.value) {
        loadComposants({ itemsPerPage: 200, force: true }).catch((error: unknown) => {
          console.error('Erreur lors du chargement des composants:', error)
        })
      }
    }
  },
)

const updateValue = (value: string | number | null | undefined) => {
  if (value === undefined || value === null || value === '') {
    emit('update:modelValue', null)
    return
  }
  emit('update:modelValue', String(value))
}

const formatDescription = (option: any) => {
  const parts: string[] = []
  if (option?.reference) {
    parts.push(option.reference)
  }
  if (option?.prix !== undefined && option.prix !== null) {
    const price = Number(option.prix)
    if (!Number.isNaN(price)) {
      parts.push(`${price.toFixed(2)} €`)
    }
  }
  return parts.length ? parts.join(' • ') : 'Sans référence'
}
</script>
