<script setup lang="ts">
import { computed, watch, onBeforeMount, type ComputedRef } from 'vue';
import { useLocale } from 'vuetify';
import { ITEMS_PER_PAGE } from '@/constants/static';
import { useGroupsStore } from '@/stores/groups';
import { isDeleted, isModifiedDate } from '@/mixins/item-validation';
import { Group } from '@/types/group';
import Moment from '@/plugins/moment';

defineProps<{
  tableHeight: number;
}>();

const { t } = useLocale();

const $groups = useGroupsStore();

const headers: ComputedRef<any[]> = computed(() => [
  { title: t('$vuetify.groups.heads.id'), key: 'ID' },
  { title: t('$vuetify.groups.heads.name'), key: 'name' },
  { title: t('$vuetify.groups.heads.issuer'), key: 'issuer' },
  { title: t('$vuetify.groups.heads.status'), key: 'status' },
  { title: t('$vuetify.groups.heads.created-at'), key: 'createdAt' },
  { title: t('$vuetify.groups.heads.updated-at'), key: 'updatedAt' },
  {
    title: t('$vuetify.misc.actions'),
    key: 'actions',
    sortable: false,
    align: 'center',
  },
]);

// Actions
const editGroup = (g: Group) => {
  $groups.openModal();
  $groups.startEditGroup(g);
};

// Status
const calculateStatus = (group: Group) => {
  return isDeleted(group.deletedAt)
    ? t('$vuetify.groups.statuses.deleted')
    : t('$vuetify.groups.statuses.active');
};
const calculateStatusColor = (group: Group) => {
  return isDeleted(group.deletedAt) ? 'text-error' : '';
};

onBeforeMount($groups.getAll);
watch(() => [$groups.page, $groups.perPage, $groups.orderBy], $groups.getAll);
watch(
  () => [$groups.search],
  () => $groups.searchWithCooldown(1 * 1000),
);
</script>

<template>
  <v-data-table-server
    v-model="$groups.selected"
    :search="$groups.search"
    :header-props="{ nowrap: true }"
    :headers="headers"
    :items="$groups.all"
    :items-per-page-options="ITEMS_PER_PAGE"
    :items-per-page="$groups.perPage"
    :items-length="$groups.cursor?.totalRows"
    :loading="$groups.loading"
    :height="tableHeight - 62"
    item-value="ID"
    fixed-footer
    fixed-header
    show-select
    checkbox-color="primary"
    hover
    density="compact"
    style="--fixed: 10"
    @update:sort-by="$groups.setSort"
    @update:page="$groups.setPage"
    @update:itemsPerPage="$groups.setPerPage"
  >
    <!-- Group name -->
    <template v-slot:item.name="{ item }">
      <template v-if="item.name?.length">
        <a
          :href="`?group_id=${item.ID}`"
          target="_blank"
          class="flex items-center gap-1 text-nowrap text-primary"
        >
          <span class="font-bold">{{ item.name }}</span>
          <span class="mso text-sm">open_in_new</span>
        </a>
      </template>
      <span v-else class="text-nowrap">—</span>
    </template>
    <!-- Group issuer -->
    <template v-slot:item.issuer="{ item }">
      <template v-if="item.issuer">
        <a
          :href="`?input=${item.issuer.ID}`"
          target="_blank"
          class="flex items-center gap-1 text-nowrap text-primary"
        >
          <span class="font-bold">{{
            `${item.issuer.email} (ID: ${item.issuer.ID})`
          }}</span>
          <span class="mso text-sm">open_in_new</span>
        </a>
      </template>
      <span v-else class="text-nowrap">—</span>
    </template>
    <!-- Group status -->
    <template v-slot:item.status="{ item }">
      <span :class="calculateStatusColor(item)">
        {{ calculateStatus(item) }}
      </span>
    </template>
    <!-- Created at -->
    <template v-slot:item.createdAt="{ item }">
      <template v-if="isModifiedDate(item.createdAt)">
        <span class="text-nowrap">
          {{ Moment.$moment(item.createdAt).format('DD MMM YYYY HH:mm') }}
        </span>
      </template>
      <span v-else class="text-nowrap">—</span>
    </template>
    <!-- Updated at -->
    <template v-slot:item.updatedAt="{ item }">
      <template v-if="isModifiedDate(item.updatedAt)">
        <span class="text-nowrap">
          {{ Moment.$moment(item.updatedAt).format('DD MMM YYYY HH:mm') }}
        </span>
      </template>
      <span v-else class="text-nowrap">—</span>
    </template>
    <!-- Actions -->
    <template v-slot:item.actions="{ item }">
      <v-btn
        icon
        size="small"
        variant="text"
        density="comfortable"
        class="mr-1"
        :disabled="isDeleted(item.deletedAt)"
        @click="editGroup(item)"
      >
        <span class="mso text-xl">edit</span>
      </v-btn>
      <!-- Delete -->
      <v-btn
        icon
        size="small"
        variant="text"
        density="comfortable"
        :disabled="isDeleted(item.deletedAt)"
      >
        <span class="mso text-xl">close</span>
      </v-btn>
    </template>
  </v-data-table-server>
</template>
