<script setup lang="ts">
import { useLocale } from 'vuetify';
import { UsersPageTabs } from '@/enums/user-tab.enum';
import { useUsersStore } from '@/stores/users';
import { useGroupsStore } from '@/stores/groups';
import ErrorPlate from '@/components/ErrorPlate.vue';
import AddUser from './components/AddUser.vue';
import AddGroup from './components/AddGroup.vue';
import UsersTab from './components/UsersTab.vue';
import GroupsTab from './components/GroupsTab.vue';
import { setURIParams } from '@/mixins/query-params';
import { OrderBy } from '@/types/order-by';

// Common variables
const { t } = useLocale();

const $users = useUsersStore();
const $groups = useGroupsStore();

const tableHeight: Ref<number> = ref(500);
setInterval(() => {
  const wY = window.innerHeight;
  const el = document.getElementById('table');
  if (el) {
    const bb = el.getBoundingClientRect();
    tableHeight.value = wY - bb.top;
  }
}, 100);

//
// MARK: Tabs
//
const tab: Ref<UsersPageTabs> = ref(UsersPageTabs.USERS);
const parseURLSearch = () => {
  const params = new URLSearchParams(window.location.search);
  // Get tab
  if (params.has('tab')) {
    tab.value = Number(params.get('tab'));
  }
  // Get page
  if (params.has('page')) {
    const v = Number(params.get('page'));
    tab.value === UsersPageTabs.USERS ? $users.setPage(v) : $groups.setPage(v);
  }
  // Get per page count
  if (params.has('count')) {
    const v = Number(params.get('count'));
    tab.value === UsersPageTabs.USERS
      ? $users.setPerPage(v)
      : $groups.setPerPage(v);
  }
  // Get sort
  if (params.has('key') && params.has('order')) {
    const v: OrderBy = {
      key: params.get('key') ?? 'ID',
      order: params.get('order') ?? 'asc',
    };
    tab.value === UsersPageTabs.USERS
      ? $users.setSort([v])
      : $groups.setSort([v]);
  }
  // Get search
  if (params.has('input')) {
    const v = params.get('input') ?? '';
    tab.value === UsersPageTabs.USERS
      ? ($users.search = v)
      : ($groups.search = v);
  }
  if (params.has('group_id')) {
    const v = params.get('group_id') ?? '';
    if (v?.length > 0) {
      tab.value = UsersPageTabs.USERS;
      $users.setGroupId(v);
      $users.search = '';
    }
  }
};
onBeforeMount(() => {
  parseURLSearch();
  tab.value === UsersPageTabs.USERS ? $groups.getAll() : $users.getAll();
});
onUpdated(parseURLSearch);
watch(tab, () => {
  setURIParams(new URLSearchParams([['tab', String(tab.value)]]), !tab.value);
  resetActions();
  getAll();
});

//
// MARK: Creation
//
const openCreationModal = () => {
  tab.value === UsersPageTabs.USERS ? $users.openModal() : $groups.openModal();
};

//
// MARK: Search model
//
const $search: WritableComputedRef<string> = computed({
  get() {
    return tab.value === UsersPageTabs.USERS ? $users.search : $groups.search;
  },
  set(v: string) {
    tab.value === UsersPageTabs.USERS
      ? ($users.search = v)
      : ($groups.search = v);
  },
});
//
// MARK: Error
//
const $error: ComputedRef<string> = computed(() =>
  tab.value === UsersPageTabs.USERS ? $users.error : $groups.error,
);

//
// MARK: Common functions
//
const getAll = () => {
  tab.value === UsersPageTabs.USERS ? $users.getAll() : $groups.getAll();
};
const clearSearch = () => {
  tab.value === UsersPageTabs.USERS
    ? ($users.search = '')
    : ($groups.search = '');
};
const resetActions = () => {
  $users.resetGroupId();
  $users.resetSelected();
  $groups.resetSelected();
};
</script>

<template>
  <div>
    <!-- Header -->
    <v-app-bar prominent class="elevation-0 border-b">
      <!-- Selected -->
      <div
        v-if="
          $users.groupId?.length > 0 ||
          $groups.selected?.length ||
          $users.selected?.length
        "
        class="flex items-center absolute h-full w-full left-0 top-0 table-actions z-[99]"
      >
        <!-- Clear -->
        <v-btn
          color="primary"
          icon
          size="small"
          class="ml-2 mr-3"
          @click="resetActions()"
        >
          <span class="mso text-3xl">close</span>
        </v-btn>
        <!-- Count -->
        <span class="text-h6 z-[100]">{{
          !$groups.selected?.length && !$users.selected?.length
            ? t('$vuetify.users.selected-group', [$users.groupId])
            : t('$vuetify.misc.selected', [
                tab === UsersPageTabs.USERS
                  ? $users.selected?.length
                  : $groups.selected?.length,
              ])
        }}</span>
      </div>

      <!-- Title -->
      <span class="text-h6 ml-5 mr-10">{{
        t(
          tab === UsersPageTabs.USERS
            ? '$vuetify.users.title'
            : '$vuetify.users.tabs.groups',
        )
      }}</span>

      <!-- Create group/user -->
      <v-btn
        color="primary"
        variant="text"
        class="mr-3 px-3"
        @click="openCreationModal()"
      >
        <span class="mso mr-1 text-xl">{{
          tab === UsersPageTabs.USERS ? 'person_add' : 'group_add'
        }}</span>
        <span>{{
          t(
            tab === UsersPageTabs.USERS
              ? '$vuetify.actions.create-user'
              : '$vuetify.actions.create-group',
          )
        }}</span>
      </v-btn>

      <!-- User creation modal -->
      <AddUser v-model="$users.createModal" />
      <!-- Group creation modal -->
      <AddGroup v-model="$groups.createModal" />

      <!-- Refresh users -->
      <v-btn class="px-3" color="primary" variant="text" @click="getAll()">
        <span class="mso mr-1 text-xl">refresh</span>
        <span>{{ t('$vuetify.actions.refresh') }}</span>
      </v-btn>
    </v-app-bar>

    <!-- Tabs -->
    <v-tabs
      v-model="tab"
      color="primary"
      class="border-b"
      density="comfortable"
      bg-color="surface"
      :disabled="$users.groupId?.length > 0"
    >
      <v-tab :value="UsersPageTabs.USERS">{{
        t('$vuetify.users.tabs.users')
      }}</v-tab>
      <v-tab :value="UsersPageTabs.GROUPS">{{
        t('$vuetify.users.tabs.groups')
      }}</v-tab>
    </v-tabs>

    <!-- Search -->
    <v-card-title class="p-0 w-full">
      <v-text-field
        v-model="$search"
        density="compact"
        :label="t('$vuetify.users.search')"
        prepend-inner-icon="mdi-magnify"
        variant="solo-filled"
        class="border-b"
        :rounded="false"
        flat
        clearable
        hide-details
        single-line
        @click:clear="clearSearch()"
      ></v-text-field>
    </v-card-title>

    <!-- Error -->
    <ErrorPlate :error="$error" block />

    <div class="h-0" id="table"></div>

    <v-tabs-window v-model="tab">
      <!-- Loader -->
      <transition name="fade">
        <table-loader v-if="$users.loading || $groups.loading" />
      </transition>

      <!-- USERS -->
      <v-tabs-window-item :value="UsersPageTabs.USERS">
        <v-card flat rounded="0" :height="`${tableHeight}px`">
          <!-- Data -->
          <users-tab :tableHeight="tableHeight" />
        </v-card>
      </v-tabs-window-item>

      <!-- GROUPS -->
      <v-tabs-window-item :value="UsersPageTabs.GROUPS">
        <!-- Data -->
        <v-card flat rounded="0" :height="`${tableHeight}px`">
          <groups-tab :tableHeight="tableHeight" />
        </v-card>
      </v-tabs-window-item>
    </v-tabs-window>
  </div>
</template>
