<script setup lang="ts">
/**
 * Props-driven autocomplete composition. Wraps the shadcn Combobox
 * primitive with client-side search filtering.
 *
 *   <AutoCompleteOption v-model="city" :options="[...]" label="City" />
 */
import { computed, ref } from "vue"
import { Search } from "@lucide/vue"
import type { SelectOptionLike } from "@/definitions/shared/select-options"
import {
  Combobox,
  ComboboxAnchor,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
} from "@/components/ui/combobox"
import { FieldFrame } from "@/components/ui/field-frame"

export interface AutoCompleteOptionProps {
  modelValue?: string | number | null
  options?: SelectOptionLike[]
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  placeholder?: string
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
  minSearchLength?: number
}

const props = withDefaults(defineProps<AutoCompleteOptionProps>(), {
  errors: () => [],
  options: () => [],
  minSearchLength: 0,
})

const model = defineModel<string | number | null>("modelValue")

interface NormalisedOption {
  label: string
  value: string
  disabled: boolean
}

function normaliseOption(opt: SelectOptionLike): NormalisedOption {
  if (typeof opt === "string") {
    return { label: opt, value: opt, disabled: false }
  }
  return {
    label: opt.label,
    value: String(opt.value),
    disabled: Boolean(opt.disabled),
  }
}

const normalised = computed<NormalisedOption[]>(() =>
  (props.options ?? []).map(normaliseOption),
)

const query = ref("")

const filtered = computed<NormalisedOption[]>(() => {
  const q = query.value.trim().toLowerCase()
  if (q.length < props.minSearchLength) {
    return normalised.value
  }
  if (q === "") {
    return normalised.value
  }
  return normalised.value.filter((o) => o.label.toLowerCase().includes(q))
})

const currentValue = computed<string | undefined>(() => {
  if (model.value === undefined || model.value === null) {
    return undefined
  }
  return String(model.value)
})

function onUpdate(next: unknown): void {
  if (Array.isArray(next)) {
    model.value = next[0] === undefined ? null : (next[0] as string | number)
    return
  }
  model.value = next === undefined ? null : (next as string | number)
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <Combobox
      :model-value="currentValue"
      :disabled="disabled || readonly"
      @update:model-value="onUpdate"
    >
      <ComboboxAnchor
        :data-element-name="name ?? undefined"
        :class="errors.length ? 'border-destructive ring-destructive' : ''"
      >
        <Search class="mr-2 h-4 w-4 shrink-0 opacity-50" />
        <ComboboxInput
          :id="id"
          v-model="query"
          :placeholder="placeholder ?? 'Search…'"
        />
      </ComboboxAnchor>
      <ComboboxContent>
        <ComboboxEmpty>No matches.</ComboboxEmpty>
        <ComboboxItem
          v-for="opt in filtered"
          :key="opt.value"
          :value="opt.value"
          :disabled="opt.disabled"
        >
          <ComboboxItemIndicator />
          {{ opt.label }}
        </ComboboxItem>
      </ComboboxContent>
    </Combobox>
  </FieldFrame>
</template>
