<template>
  <section class="space-y-4">
    <header>
      <h3 class="text-lg font-semibold text-base-content">Génération de référence automatique</h3>
      <p class="mt-1 text-sm text-base-content/70">
        Cliquez sur un champ pour l'insérer dans la formule. Vous pouvez aussi taper du texte libre (séparateurs, préfixes…).
      </p>
    </header>

    <div class="rounded-lg border border-base-300 p-4 space-y-4">
      <div v-if="fieldNames.length" class="flex flex-wrap gap-2">
        <button
          v-for="name in fieldNames"
          :key="name"
          type="button"
          class="btn btn-xs btn-outline btn-primary font-mono"
          :disabled="disabled"
          @click="insertField(name)"
        >
          {{ name }}
        </button>
      </div>
      <p v-else class="text-sm text-base-content/50 italic">
        Aucun champ personnalisé défini dans la structure.
      </p>

      <div>
        <label class="label" for="reference-formula">
          <span class="label-text">Formule</span>
        </label>
        <input
          id="reference-formula"
          ref="inputRef"
          :value="modelValue"
          type="text"
          class="input input-bordered w-full font-mono"
          placeholder="Ex: SNU {serie}-{diametre}/{type}"
          :disabled="disabled"
          @input="emit('update:modelValue', ($event.target as HTMLInputElement).value || null)"
        />
        <p class="mt-1 text-xs text-base-content/60">
          Laissez vide si ce type n'utilise pas de référence automatique.
        </p>
      </div>

      <div v-if="modelValue" class="rounded bg-base-200 px-3 py-2 text-sm">
        <span class="text-base-content/70">Aperçu :</span>
        <span class="ml-1 font-mono font-semibold">{{ preview }}</span>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'

interface CustomField {
  name: string
  type: string
}

const props = defineProps<{
  modelValue: string | null | undefined
  customFields: CustomField[]
  disabled?: boolean
}>()

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

const inputRef = ref<HTMLInputElement | null>(null)

const fieldNames = computed(() =>
  props.customFields.map(f => f.name).filter((n): n is string => Boolean(n)),
)

const previewExamples: Record<string, string> = {
  text: 'VALEUR',
  number: '123',
  select: 'OPTION',
  boolean: 'OUI',
  date: '2026-01-01',
}

const preview = computed(() => {
  if (!props.modelValue) return ''
  const fieldMap = new Map<string, string>()
  for (const f of props.customFields) {
    if (f.name) {
      fieldMap.set(f.name, previewExamples[f.type] ?? 'VALEUR')
    }
  }
  return props.modelValue.replace(/\{([^}]+)\}/gu, (_, name) => fieldMap.get(name) ?? '???')
})

const insertField = (fieldName: string) => {
  const placeholder = `{${fieldName}}`
  const input = inputRef.value
  const current = props.modelValue ?? ''
  if (!input) {
    emit('update:modelValue', current + placeholder)
    return
  }
  const start = input.selectionStart ?? current.length
  const end = input.selectionEnd ?? start
  const updated = current.slice(0, start) + placeholder + current.slice(end)
  emit('update:modelValue', updated)
  nextTick(() => {
    const newPos = start + placeholder.length
    input.focus()
    input.setSelectionRange(newPos, newPos)
  })
}
</script>
