<template>
    <div>
        <div class="text-sm text-gray-600 pb-3" v-text="intro" v-if="intro"></div>
        <label class="w-full border border-solid border-gray-500 focus-within:border-primary rounded-lg relative flex" :for="id">
            <select
                v-if="!allowcustom"
                :id="id"
                v-model="inner"
                :name="name"
                class="bg-white group-[.info]:bg-blue-200 rounded-lg focus:outline-none text-gray-600 text-left py-1 px-2 @sm:py-2 @sm:group-[.info]:py-1 text-sm @sm:text-base @sm:group-[.info]:text-sm @sm:px-3 @sm:group-[.info]:px-2 w-full"
            >
                <option :value="null">-- keine Angabe --</option>
                <option v-for="(option, index) in options" :key="index" :value="option.id" v-text="option.name"></option>
            </select>
            <input
                v-if="allowcustom"
                v-model="inner"
                class="bg-white group-[.info]:bg-blue-200 rounded-lg focus:outline-none text-gray-600 text-left py-1 px-2 @sm:py-2 @sm:group-[.info]:py-1 text-sm @sm:text-base @sm:group-[.info]:text-sm @sm:px-3 @sm:group-[.info]:px-2 w-full"
                type="text"
                :list="`${id}-list`"
            />
            <datalist v-if="allowcustom" :id="`${id}-list`">
                <option v-for="(option, index) in options" :key="index" :value="option.id" v-text="option.name"></option>
            </datalist>
            <div v-if="hint" class="absolute right-0 mr-2 flex items-center h-full">
                <hint :value="hint"></hint>
            </div>
            <field-label :name="label" class="group-[.info]:bg-blue-200" :required="required"></field-label>
        </label>
    </div>
</template>

<script setup>
import {computed} from 'vue';
import FieldLabel from '../FieldLabel.vue';
import Hint from '../Hint.vue';

const emit = defineEmits(['update:modelValue']);
const props = defineProps({
    modelValue: {
        required: true,
        validator: (value) => value === null || typeof value === 'string',
    },
    required: {
        required: false,
        type: Boolean,
        default: () => false,
    },
    name: {
        required: true,
        type: String,
    },
    id: {
        required: true,
        type: String,
    },
    label: {
        required: true,
        type: String,
    },
    options: {
        required: true,
        type: Array,
    },
    hint: {
        required: false,
        validator: (value) => value === null || typeof value === 'string',
        default: () => null,
    },
    allowcustom: {
        required: true,
        type: Boolean,
    },
    intro: {
        required: false,
        default: () => '',
    },
});

const inner = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
});
</script>
