<script setup lang="ts">
/**
 * Props-driven data-model picker composition. Searchable combobox over a
 * list of field-path keys supplied via `dataModelKeys`. Used by the
 * FormBuilder inspector to pick a data-model key; the eventual async
 * lookup service will swap in the same surface area.
 *
 *   <DataModelPicker
 *     v-model="key"
 *     label="Field"
 *     :data-model-keys="['first_name', 'last_name', 'email']"
 *   />
 */
import { computed, ref } from "vue"
import { Code2 } from "@lucide/vue"
import {
  Combobox,
  ComboboxAnchor,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
} from "@/components/ui/combobox"
import { FieldFrame } from "@/components/ui/field-frame"

export interface DataModelPickerProps {
  modelValue?: string | null
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  placeholder?: string
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
  /** Candidate field paths to choose from. */
  dataModelKeys?: string[]
}

const props = withDefaults(defineProps<DataModelPickerProps>(), {
  errors: () => [],
  dataModelKeys: () => [],
})

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

const query = ref<string>("")

const filtered = computed<string[]>(() => {
  const q = query.value.trim().toLowerCase()
  const keys = Array.isArray(props.dataModelKeys) ? props.dataModelKeys : []
  if (!q) {
    return keys.slice(0, 200)
  }
  return keys.filter((k) => k.toLowerCase().includes(q)).slice(0, 200)
})

function onSelect(value: unknown): void {
  model.value = typeof value === "string" ? value : ""
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <Combobox
      :model-value="model ?? ''"
      :disabled="disabled"
      @update:model-value="onSelect"
    >
      <ComboboxAnchor
        :data-element-name="name ?? undefined"
        :data-readonly="readonly || undefined"
      >
        <Code2 class="mr-2 size-4 shrink-0 opacity-50" />
        <ComboboxInput
          v-model="query"
          :placeholder="placeholder ?? 'data.key.path'"
          :readonly="readonly"
          :required="required"
          class="font-mono text-sm"
        />
      </ComboboxAnchor>
      <ComboboxContent>
        <ComboboxEmpty>No fields match.</ComboboxEmpty>
        <ComboboxItem v-for="key in filtered" :key="key" :value="key">
          <ComboboxItemIndicator />
          <span class="font-mono">{{ key }}</span>
        </ComboboxItem>
      </ComboboxContent>
    </Combobox>
  </FieldFrame>
</template>
