<template>
  <q-table
    flat
    bordered
    ref="tableRef"
    :title="$t('attendees')"
    title-class="text-bold text-blue-9"
    :no-data-label="$t('noDataAvailable')"
    :loading-label="$t('loading')"
    :rows-per-page-label="$t('recordsPerPage')"
    :selected-rows-label="(val) => val + ' ' + $t('recordSelected')"
    :rows="attendees"
    :columns="columns"
    row-key="id"
    v-model:pagination="pagination"
    :loading="loading"
    :filter="filter"
    :selection="selectOption ? 'multiple' : 'none'"
    v-model:selected="selected"
    binary-state-sort
    dense
    class="bigger-table-text"
  >
    <!--top left of event table-->
    <template v-slot:top-left>
      <q-btn-group push flat style="color: grey">
        <q-btn
          v-if="user.isPermittedTo('events', 'write')"
          dense
          flat
          icon="person"
          @click="openAttendanceDialog"
          ><q-badge floating transparent color="primary" text-color="primary-text">+</q-badge>
          <q-tooltip>{{ $t('addNewAttendees') }}</q-tooltip>
        </q-btn>
        <q-btn
          v-if="user.isPermittedTo('events', 'write')"
          dense
          flat
          style="color: grey"
          :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
          @click="selectOption = !selectOption"
        >
          <q-tooltip>{{ $t('selectAttendeesOptions') }}</q-tooltip>
        </q-btn>
      </q-btn-group>
      <div v-if="selectOption && selected.length > 0">
        <q-btn flat dense icon="more_vert" @click="openSubmenu = true" />
        <q-menu v-if="openSubmenu" anchor="bottom middle" self="top middle">
          <q-item
            clickable
            v-close-popup
            @click="openRemoveDialog(...selected)"
            class="text-negative"
            >{{ $t('delete') }}</q-item
          >
        </q-menu>
      </div>
      <div v-if="selectOption && selected.length > 0" class="q-ml-md text-weight-bold">
        {{ $t('selected') }}: {{ selected.length }}
      </div>
    </template>
    <!--top right of event table-->
    <template v-slot:top-right>
      <q-input filled dense debounce="300" v-model="filter" :placeholder="$t('search')">
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>
    </template>
    <!--body of event table-->
    <template v-slot:body-cell="props">
      <q-td v-if="props.col.field === 'attendees'" :props="props">
        <q-btn v-if="props.value !== null && props.value.length > 0" dense flat icon="people"
          ><q-badge color="primary" text-color="primary-text" floating transparent>{{
            props.row.attendees.length
          }}</q-badge></q-btn
        >
      </q-td>
      <q-td v-else :props="props">
        {{ props.value }}
      </q-td>
    </template>
    <template v-slot:body-cell-option="props">
      <q-td :props="props">
        <q-btn
          v-if="user.isPermittedTo('events', 'delete')"
          flat
          dense
          @click="openRemoveDialog(props.row)"
          color="negative"
          icon="delete"
        />
      </q-td>
    </template>
  </q-table>
  <DialogFrame ref="attendanceDialog" :header-title="$t('members')" :width="700" :height="500">
    <MembersTable
      add-attendees
      :compare-members="attendees"
      v-on:update-event="(val) => updateTable(val)"
      :event-id="localEvent?.id ?? 0"
    />
  </DialogFrame>

  <OkDialog
    ref="okDialog"
    :dialog-label="$t('delete')"
    :text="$t('doYouWantToDelete') + ' ' + deleteText"
    label-color="red"
    :button-cancel-label="$t('cancel')"
    :button-ok-label="$t('confirm')"
    :button-ok-flat="false"
    button-ok-color="red"
    v-on:update-confirm="(val) => removeAttendees(...val)"
  ></OkDialog>
</template>

<script setup lang="ts">
//imports
import { appApi } from 'src/boot/axios';
import { onMounted, type PropType, ref } from 'vue';
import type { Members } from 'src/vueLib/models/member';
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useAttendeesTable } from '../attendees/AttendeesTable';
import { useUserStore } from 'src/vueLib/login/userStore';
import type { Event } from 'src/vueLib/models/event';
import MembersTable from '../members/MembersTable.vue';
import { i18n } from 'src/boot/lang';

//use constants and function of imports
const { attendees, pagination, loading, columns, updateAttendees } = useAttendeesTable();

//define given properties
const props = defineProps({
  event: {
    type: Object as PropType<Event>,
    required: true,
  },
  eventArray: { type: Number, default: 0, required: true },
});

// define emits
const emit = defineEmits(['update']);

// definitions
const { NotifyResponse } = useNotify();
const attendanceDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const selectOption = ref(false);
const localEvent = ref<Event>();
const selected = ref<Members>([]);
const openSubmenu = ref(false);
const filter = ref('');
const user = useUserStore();

// load at page mount
onMounted(() => {
  localEvent.value = props.event;
  attendees.value = props.event.attendees ?? [];
});

//opens attendance dialog
function openAttendanceDialog() {
  attendanceDialog.value?.open();
}

//opens remove dialog
function openRemoveDialog(...attendees: Members) {
  if (attendees.length === 1) {
    deleteText.value = "'";
    if (attendees[0]?.firstName && attendees[0]?.lastName) {
      deleteText.value += attendees[0]?.firstName + ' ' + attendees[0]?.lastName;
    }
    deleteText.value += "'";
  } else {
    deleteText.value = String(attendees.length) + ' ' + i18n.global.t('attendees');
  }

  okDialog.value?.open(attendees);
}

//remove attendees from database
async function removeAttendees(...removeAttendees: Members) {
  if (!localEvent.value) {
    NotifyResponse('event is empty', 'error');
    return;
  }

  localEvent.value.attendees = removeAttendees;

  await appApi
    .post('events/delete/attendees', localEvent.value)
    .then(() => {
      selected.value = [];
      if (localEvent.value?.attendees !== undefined && localEvent.value?.attendees.length > 1) {
        NotifyResponse(i18n.global.t('deleteAttendees'), 'warning');
      } else {
        NotifyResponse(i18n.global.t('deleteAttendee'), 'warning');
      }
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
  await updateAttendees(props.eventArray);
  emit('update', -removeAttendees.length);
}

async function updateTable(amount: number) {
  await updateAttendees(props.eventArray);
  emit('update', amount);
}
</script>

<style>
.bigger-table-text .q-table__middle td {
  font-size: 14px;
}

.bigger-table-text .q-table__top,
.bigger-table-text .q-table__bottom,
.bigger-table-text th {
  font-size: 14px;
}
</style>
