<template>
  <div class="q-pa-md">
    <q-table
      flat
      bordered
      ref="tableRef"
      title="Members"
      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="members"
      :columns="columns"
      row-key="id"
      v-model:pagination="pagination"
      :loading="loading"
      :filter="filter"
      :selection="selectOption ? 'multiple' : 'none'"
      v-model:selected="selected"
      binary-state-sort
      class="bigger-table-text"
    >
      <template v-slot:top-left>
        <q-btn-group push flat style="color: grey">
          <q-btn dense flat icon="add" @click="openAllValueDialog(null)">
            <q-tooltip>{{ $t('addNewMember') }}</q-tooltip>
          </q-btn>
          <q-btn
            dense
            flat
            style="color: grey"
            :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
            @click="selectOption = !selectOption"
          >
            <q-tooltip>{{ $t('selectMemberOptions') }}</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="upload" @click="openUploadDialog">
            <q-tooltip>{{ $t('importCSV') }}</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>
      <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>
      <template v-slot:body-cell="props">
        <q-td
          :props="props"
          :class="getRowClass(props.row)"
          @click="openSingleValueDialog(props.col.label, props.col.name, props.row)"
        >
          {{ props.value }}
        </q-td>
      </template>
      <template v-slot:body-cell-cake="props">
        <q-td :props="props" :class="getRowClass(props.row)">
          <q-icon
            :name="isXDaysBeforeAnnualDate(props.row.birthday, 1) ? 'cake' : ''"
            :color="'red'"
            size="md"
          />
        </q-td>
      </template>
      <template v-slot:body-cell-option="props">
        <q-td :props="props">
          <q-btn flat dense icon="more_vert" @click="openSubmenu = true" />
          <q-menu v-if="openSubmenu" anchor="top right" self="top left">
            <q-item
              clickable
              v-close-popup
              @click="openAllValueDialog(props.row)"
              class="text-primary"
              >{{ $t('edit') }}</q-item
            >
            <q-item
              clickable
              v-close-popup
              @click="openRemoveDialog(props.row)"
              class="text-negative"
              title="zu"
              >{{ $t('delete') }}</q-item
            >
          </q-menu>
        </q-td>
      </template>
    </q-table>
  </div>
  <EditOneDialog ref="editOneDialog" v-on:update="updateMembers"></EditOneDialog>
  <EditAllDialog ref="editAllDialog" v-on:update="updateMembers"></EditAllDialog>
  <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) => removeMember(...val)"
  ></OkDialog>
  <UploadDialog ref="uploadDialog" @update-upload="updateMembers"> </UploadDialog>
</template>

<script setup lang="ts">
import { appApi } from 'src/boot/axios';
import { ref, onMounted } from 'vue';
import type { Member, Members } from 'src/vueLib/models/member';
import EditOneDialog from 'src/components/EditOneDialog.vue';
import EditAllDialog from 'src/components/MemberEditAllDialog.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useMemberTable } from './MembersTable';
import UploadDialog from 'src/components/UploadDialog.vue';
import { databaseName } from './MembersTable';

export interface MemberDialog {
  getSelected: () => Members;
}

const { NotifyResponse } = useNotify();
const editOneDialog = ref();
const editAllDialog = ref();
const uploadDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const selectOption = ref(false);
const selected = ref<Members>([]);
const openSubmenu = ref(false);
const filter = ref('');

const {
  members,
  pagination,
  loading,
  columns,
  getRowClass,
  updateMembers,
  isXDaysBeforeAnnualDate,
} = useMemberTable();

//load on mounting page
onMounted(() => {
  loading.value = true;

  appApi
    .post('secure/database/open', { dbPath: databaseName.value, create: true })
    .then(() => {
      updateMembers();
    })
    .catch((err) => NotifyResponse(err, 'error'))

    .finally(() => {
      loading.value = false;
    });
});

// opens dialog for all member values
function openSingleValueDialog(label: string, field: string, member: Member) {
  editOneDialog.value?.open(label, field, member);
}

//opens dialog for one value
function openAllValueDialog(member: Member | null) {
  editAllDialog.value?.open(member);
}

//opens remove dialog
function openRemoveDialog(...members: Members) {
  if (members.length === 1) {
    deleteText.value = "'";
    if (members[0]?.firstName !== undefined) {
      deleteText.value += members[0]?.firstName + ' ';
    }
    if (members[0]?.lastName !== undefined) {
      deleteText.value += members[0]?.lastName;
    }
    deleteText.value += "'";
  } else {
    deleteText.value = String(members.length) + ' members';
  }
  okDialog.value?.open(members);
}

//opens uploader dialog
function openUploadDialog() {
  uploadDialog.value?.open();
}

//remove member from database
function removeMember(...removeMembers: Members) {
  const memberIds: number[] = [];

  removeMembers.forEach((member: Member) => {
    memberIds.push(member.id);
  });

  appApi
    .post('secure/members/delete', { ids: memberIds })
    .then(() => {
      updateMembers();
      selected.value = [];
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
}

//const blinkingId = ref<number | null>(null);

// function triggerBlink(id: number) {
//   blinkingId.value = id;

//   // Optional: stop blinking after 3 seconds
//   setTimeout(() => {
//     blinkingId.value = null;
//   }, 3000);
// }

function getSelected(): Members {
  if (selected.value.length === 0) return [];
  return selected.value;
}
defineExpose({
  getSelected,
});
</script>

<style>
@keyframes blink-yellow {
  0%,
  100% {
    background-color: yellow;
  }
  50% {
    background-color: transparent;
  }
}

.blink-yellow {
  animation: blink-yellow 1.5s step-start 6 !important;
}

.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>
