<template>
  <!-- notice dialogRef here -->
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin">
      <q-card-section>
        <div v-if="isInvite" class="text-h6">Zum Dienst einladen</div>
        <div v-else class="text-h6">Dienst tauschen</div>
      </q-card-section>
      <q-separator />
      <q-card-section>
        <q-select
          v-model="invitees"
          filled
          :options="otherUsers"
          :option-label="(opt) => opt.display_name"
          :multiple="isInvite"
          use-chips
          stack-label
          label="Dienste"
        >
        </q-select>
      </q-card-section>
      <!-- buttons example -->
      <q-card-actions align="right">
        <q-btn color="primary" label="Ok" @click="invite" />
        <q-btn color="primary" label="Abbrechen" @click="onDialogCancel" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { useMainStore, useUserStore } from '@flaschengeist/api';
import { useEventStore } from '../../../store';
import { useDialogPluginComponent } from 'quasar';
import { PropType, computed, defineComponent, ref } from 'vue';

export default defineComponent({
  props: {
    isInvite: {
      type: Boolean,
      default: true,
    },
    job: {
      required: true,
      type: Object as PropType<FG.Job>,
    },
  },

  emits: [...useDialogPluginComponent.emits],

  setup(props) {
    const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();

    const userStore = useUserStore();
    const mainStore = useMainStore();
    const store = useEventStore();
    const invitees = ref([] as FG.User[]);
    const otherUsers = computed(() =>
      userStore.users.filter(
        (u) =>
          u.userid !== mainStore.currentUser.userid &&
          props.job.services.findIndex((s) => s.userid === u.userid) === -1
      )
    );

    function invite() {
      void store
        .invite(props.job, invitees.value, !props.isInvite ? mainStore.currentUser : undefined)
        .then(() => onDialogOK());
    }

    return {
      invite,
      invitees,
      otherUsers,
      dialogRef,
      onDialogHide,
      onDialogCancel,
    };
  },
});
</script>