<script setup lang="ts">
import {
  computed,
  ref,
  watch,
  onBeforeMount,
  type Ref,
  type ComputedRef,
} from 'vue';
import { useLocale } from 'vuetify';
import { ITEMS_PER_PAGE } from '@/constants/static';
import { useUsersStore } from '@/stores/users';
import { UserActions } from '@/enums/user-actions.enum';
import { User } from '@/types/user';
import Moment from '@/plugins/moment';
import { isDeleted, isModifiedDate } from '@/mixins/item-validation';

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

const { t } = useLocale();

const $users = useUsersStore();

const headers: ComputedRef<any[]> = computed(() => [
  { title: t('$vuetify.users.heads.id'), key: 'ID' },
  { title: t('$vuetify.users.heads.email'), key: 'email' },
  { title: t('$vuetify.users.heads.group'), key: 'group' },
  { title: t('$vuetify.users.heads.real-name'), key: 'realName' },
  { title: t('$vuetify.users.heads.password'), key: 'isRequiredToSetPassword' },
  { title: t('$vuetify.users.heads.status'), key: 'isActive' },
  { title: t('$vuetify.users.heads.last-visit'), key: 'lastLogin' },
  { title: t('$vuetify.users.heads.created-at'), key: 'createdAt' },
  { title: t('$vuetify.users.heads.updated-at'), key: 'updatedAt' },
  {
    title: t('$vuetify.misc.actions'),
    key: 'actions',
    sortable: false,
    align: 'center',
  },
]);
const actions = computed(() => [
  {
    title: t('$vuetify.actions.edit'),
    value: UserActions.EDIT,
    blocked: false,
    onClick: (u: User) => editUser(u),
  },
  {
    title: t('$vuetify.actions.block'),
    value: UserActions.BLOCK,
    blocked: false,
  },
  {
    title: t('$vuetify.actions.reset-password'),
    value: UserActions.RESET_PASSWORD,
    blocked: false,
  },
  {
    title: t('$vuetify.actions.unblock'),
    value: UserActions.UNBLOCK,
    blocked: true,
  },
]);
// Actions
const editUser = (u: User) => {
  $users.openModal();
  $users.startEditUser(u);
};

// Status
const calculateUserStatus = (user: User) => {
  return isDeleted(user.deletedAt)
    ? t('$vuetify.users.statuses.deleted')
    : user.isActive
      ? t('$vuetify.users.statuses.active')
      : t('$vuetify.users.statuses.blocked');
};
const calculateStatusColor = (user: User) => {
  return isDeleted(user.deletedAt)
    ? 'text-error'
    : user.isActive
      ? ''
      : 'text-warning';
};
// Password status
const calculateUserPasswordStatus = (user: User) => {
  return user.isRequiredToSetPassword
    ? t('$vuetify.users.statuses.unset')
    : t('$vuetify.users.statuses.set');
};

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

<template>
  <v-data-table-server
    v-model="$users.selected"
    :search="$users.search"
    :header-props="{ nowrap: true }"
    :headers="headers"
    :items="$users.all"
    :items-per-page-options="ITEMS_PER_PAGE"
    :items-per-page="$users.perPage"
    :items-length="$users.cursor?.totalRows"
    :loading="$users.loading"
    :height="tableHeight - 62"
    item-value="ID"
    fixed-footer
    fixed-header
    show-select
    hover
    density="compact"
    style="--fixed: 10"
    @update:sort-by="$users.setSort"
    @update:page="$users.setPage"
    @update:itemsPerPage="$users.setPerPage"
  >
    <!-- Group -->
    <template v-slot:item.group="{ item }">
      <template v-if="item.group">
        <a
          :href="`?group_id=${item.group.ID}`"
          target="_blank"
          class="flex items-center gap-1 text-nowrap text-primary"
        >
          <span class="font-bold">{{ item.group.name }}</span>
          <span class="mso text-sm">open_in_new</span>
        </a>
      </template>
      <span v-else class="text-nowrap">—</span>
    </template>
    <!-- Real name -->
    <template v-slot:item.realName="{ item }">
      <span class="text-nowrap">
        {{ item.realName?.length ? item.realName : '—' }}
      </span>
    </template>
    <!-- Required to set password -->
    <template v-slot:item.isRequiredToSetPassword="{ item }">
      <span
        :class="{
          'text-error': item.isRequiredToSetPassword,
        }"
        class="text-nowrap"
      >
        {{ calculateUserPasswordStatus(item) }}
      </span>
    </template>
    <!-- User status -->
    <template v-slot:item.isActive="{ item }">
      <span :class="calculateStatusColor(item)">
        {{ calculateUserStatus(item) }}
      </span>
    </template>
    <!-- Last visit -->
    <template v-slot:item.lastLogin="{ item }">
      <template v-if="isModifiedDate(item.lastLogin)">
        <span class="text-nowrap">
          {{ Moment.$moment(item.lastLogin).format('DD MMM YYYY HH:mm') }}
        </span>
      </template>
      <span v-else class="text-nowrap">—</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-menu transition="none">
        <template v-slot:activator="{ props }">
          <v-btn
            v-bind="props"
            icon
            size="small"
            variant="text"
            density="comfortable"
            class="mr-1"
            :disabled="isDeleted(item.deletedAt)"
          >
            <span class="mso text-xl">more_vert</span>
          </v-btn>
        </template>
        <v-list class="mt-2 accent-modal" elevation="0" density="compact">
          <template v-for="(act, index) of actions">
            <v-list-item
              v-if="
                (act?.blocked && !item.isActive) ||
                (!act?.blocked && item.isActive)
              "
              :key="index"
              :value="act.value"
              lines="one"
              class="cm-mini"
              @click="act.onClick ? act.onClick(item) : null"
            >
              <v-list-item-title>{{ act.title }}</v-list-item-title>
            </v-list-item>
          </template>
        </v-list>
      </v-menu>
      <!-- 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>
