<template>
  <q-select
    v-model="selected"
    filled
    :label="label"
    :options="users"
    option-label="display_name"
    option-value="userid"
    map-options
  />
</template>

<script lang="ts">
import { computed, defineComponent, PropType, onBeforeMount } from 'vue';
import { useUserStore } from '@flaschengeist/api';

export default defineComponent({
  name: 'UserSelector',
  props: {
    label: { type: String, default: 'Benutzer' },
    modelValue: { default: undefined, type: Object as PropType<FG.User | undefined> },
  },
  emits: { 'update:modelValue': (user: FG.User) => !!user },
  setup(props, { emit }) {
    const userStore = useUserStore();

    onBeforeMount(() => {
      void userStore.getUsers(false);
    });

    const users = computed(() => userStore.users);
    const selected = computed({
      get: () => props.modelValue,
      set: (value: FG.User | undefined) => (value ? emit('update:modelValue', value) : undefined),
    });

    return {
      selected,
      users,
    };
  },
});
</script>
