<template>
  <div class="space-y-1">
    <SearchSelect
      :model-value="modelValue ?? undefined"
      :options="pieceOptions"
      :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 { usePieces } from '~/composables/usePieces'

const props = withDefaults(
  defineProps<{
    modelValue?: string | null
    placeholder?: string
    emptyText?: string
    helperText?: string
    disabled?: boolean
    typePieceId?: string | null
  }>(),
  {
    modelValue: '',
    placeholder: 'Sélectionner une pièce…',
    emptyText: 'Aucune pièce disponible',
    helperText: '',
    disabled: false,
    typePieceId: null,
  },
)

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

const { pieces, loading, loadPieces } = usePieces()

const pieceOptions = computed(() => {
  const baseOptions = Array.isArray(pieces.value) ? pieces.value : []
  if (!props.typePieceId) {
    return baseOptions
  }

  const allowedTypeId = String(props.typePieceId)
  return baseOptions.filter((piece: any) => {
    const typeId =
      piece?.typePieceId ||
      piece?.typePiece?.id ||
      null
    return typeId ? String(typeId) === allowedTypeId : false
  })
})

onMounted(() => {
  if (pieceOptions.value.length === 0) {
    loadPieces({ itemsPerPage: 200 }).catch((error: unknown) => {
      console.error('Erreur lors du chargement des pièces:', error)
    })
  }
})

watch(
  () => props.modelValue,
  (value) => {
    if (typeof value === 'string') {
      const exists = pieceOptions.value.some((piece: any) => piece.id === value)
      if (!exists && pieceOptions.value.length === 0 && !loading.value) {
        loadPieces({ itemsPerPage: 200 }).catch((error: unknown) => {
          console.error('Erreur lors du chargement des pièces:', 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>
