<template>
  <DialogFrame ref="dialog" :header-title="localTitle">
    <div class="row justify-center">
      <SearchableSelect
        class="q-mx-xl"
        dense
        autofocus
        :label="$t('event')"
        filled
        :options="events"
        option-label="name"
        option-value="id"
        v-model="selected"
        @keyup.enter="addAttendees"
        map-options
        emit-value
      ></SearchableSelect>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="addAttendees">{{ localTitle }}</q-btn>
    </div>
  </DialogFrame>
  <EditAllDialog
    ref="newEventRef"
    v-on:update="
      (val) => {
        resolveNewEvent(val);
        NotifyResponse($t('memberUpdated'));
      }
    "
  ></EditAllDialog>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import { useNotify } from 'src/vueLib/general/useNotify';
import { i18n } from 'src/boot/lang';
import type { Event, Events } from 'src/vueLib/models/event';
import type { Members } from 'src/vueLib/models/member';
import EditAllDialog from 'src/components/EventEditAllDialog.vue';
import { useAttendeesTable } from 'src/vueLib/tables/attendees/AttendeesTable';
import { useEventTable } from 'src/vueLib/tables/events/EventsTable';
import SearchableSelect from 'src/vueLib/general/SearchableSelect .vue';

const dialog = ref();
const newEventRef = ref();
const localTitle = ref('');
const events = ref<Events>([{ id: -1, name: i18n.global.t('addNewEvent'), attendees: [] }]);
const selected = ref<Event>({ id: -1, name: i18n.global.t('addNewEvent'), attendees: [] });
const localMembers = ref<Members>([]);
const { updateAttendees } = useAttendeesTable();
const { updateEvents } = useEventTable();

const props = defineProps({
  endpoint: {
    type: String,
    required: true,
  },
  queryId: {
    type: Boolean,
  },
});

const emit = defineEmits(['update-event']);
const { NotifyResponse } = useNotify();

function open(title: string, members: Members) {
  localTitle.value = title;
  localMembers.value = members;

  events.value = [{ id: -1, name: i18n.global.t('addNewEvent'), attendees: [] }];
  appApi
    .get('events')
    .then((resp) => {
      events.value.push(
        ...resp.data.map((e: Event) => ({ ...e, name: e.name + ' (' + e.date + ')' })),
      );
    })
    .catch((err) => {
      NotifyResponse(err, 'error');
    });
  dialog.value?.open();
}

async function addAttendees() {
  const payload = {
    id: Number(selected.value),
    attendees: localMembers.value,
  };
  if (selected.value.id == -1) {
    const event = await addNewEvent();
    NotifyResponse(i18n.global.t('eventAdded') + ': ' + event.name);
    payload.id = event.id;
  }

  await appApi
    .post(props.endpoint, payload)
    .then(() => {
      emit('update-event', localMembers.value);
      if (localMembers.value.length > 1) {
        NotifyResponse(i18n.global.t('attendeesAdded'));
      } else {
        NotifyResponse(i18n.global.t('attendeeAdded'));
      }
      dialog.value.close();
    })
    .catch((err) => {
      NotifyResponse(err, 'error');
    });

  await updateAttendees(0);
  updateEvents();
}

let resolveNewEvent!: (value: Event) => void;
function addNewEvent(): Promise<Event> {
  newEventRef.value?.open(null);
  return new Promise((resolve) => {
    resolveNewEvent = resolve;
  });
}

defineExpose({ open });
</script>
