<template>
  <div class="q-pa-none flex column col-grow no-scroll">
    <pn-scroll-list>
      <template #card-body-header>
        <div class="flex row q-ma-md justify-between" v-if="users.length !== 0">
          <q-input
            v-model="search"
            clearable
            clear-icon="close"
            :placeholder="$t('project_users__search')"
            dense
            class="col-grow"
            >
            <template #prepend>
              <q-icon name="mdi-magnify" />
            </template>
          </q-input>
        </div>
      </template>

      <q-list separator v-if="users.length !== 0">
        <q-slide-item
          v-for="item in displayUsers"
          :key="item.id"
          @right="handleSlide($event, item.id)"
          right-color="red"
          >
          <template #right>
            <q-icon size="lg" name="mdi-account-remove-outline"/>
          </template>
          <q-item
            :key="item.id"
            v-ripple
            clickable
            class="w100"
            @click="goUserInfo(item.id)"
            >
            <q-item-section avatar>
              <pn-auto-avatar
                :img="item.photo"
                :name="item.section1"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label lines="1" class="text-bold" v-if="item.section1">
                {{item.section1}}
              </q-item-label>
              <q-item-label lines="1" caption v-if="item.section3">
                {{item.section3}}
              </q-item-label>
              <q-item-label caption lines="2">
                <div class="flex items-center">
                  <q-icon name="telegram" v-if="item.section2_1 || item.section2_2" class="q-pr-xs" style="color: #27a7e7"/>
                  <div v-if="item.section2_1" class="q-mr-sm text-bold">{{item.section2_1}}</div>
                  <div class="text-blue" v-if="item.section2_2">{{'@' + item.section2_2}}</div>
                </div>
              </q-item-label>
            </q-item-section>
          </q-item>
        </q-slide-item>  
      </q-list>

      <div
        v-if="blockedUsers.length!==0"
        class="flex column items-center w100"
        :class="showBlockedUsers ? 'bg-grey-12' : ''"
        >
        <q-btn-dropdown
          class="w100 fix-rotate-arrow"
          color="grey"
          flat no-caps 
          @click="showBlockedUsers=!showBlockedUsers"
          dropdown-icon="arrow_drop_up"
          >
          <template #label>
            <span class="text-caption">
              {{ !showBlockedUsers
                ? $t('users__show_archive') + ' (' + blockedUsers.length +')'
                : $t('user__hide_archive')
              }}
            </span>
          </template>
        </q-btn-dropdown>

        <div class="w100" style="overflow: hidden">    
          <transition
            appear
            enter-active-class="animated slideInDown"
            leave-active-class="animated slideOutUp"
            >
            <q-list separator v-if="showBlockedUsers" class="w100">
              <q-item
                v-for = "item in blockedUsers"
                :key="item.id"
                clickable
                v-ripple
                @click="handleUnblockUser(item.id)"
                class="w100 text-grey"
                >
                <q-item-section avatar>
                  <pn-auto-avatar
                    :img="item.photo"
                    :name="item.section1"
                  />
                </q-item-section>
                <q-item-section>
                  <q-item-label lines="1" class="text-bold" v-if="item.section1">
                    {{item.section1}}
                  </q-item-label>
                  <q-item-label lines="1" caption v-if="item.section3">
                    {{item.section3}}
                  </q-item-label>
                  <q-item-label caption lines="2">
                    <div class="flex items-center">
                      <q-icon name="telegram" v-if="item.section2_1 || item.section2_2" class="q-pr-xs" style="color: #27a7e7"/>
                      <div v-if="item.section2_1" class="q-mr-sm text-bold">{{item.section2_1}}</div>
                      <div class="text-blue" v-if="item.section2_2">{{'@' + item.section2_2}}</div>
                    </div>
                  </q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </transition>
        </div>
      </div>

      <pn-onboard-btn
        v-if="users.length === 0 && usersInit"
        icon="mdi-account-outline"
        :message1="$t('project_users__onboard_msg1')"
        :message2="$t('project_users__onboard_msg2')"
        noBtn
      />
      <div
        class="flex column justify-center items-center w100"
        style="position: absolute; bottom: 0;"
        v-if="!usersInit"
        >
        <q-linear-progress indeterminate />
      </div>
    </pn-scroll-list>
  </div>

  <pn-small-dialog
    v-model="showDialogDeleteUser"
    icon="mdi-account-remove-outline"
    color="negative"
    title="user__dialog_delete_title"
    message1="user__dialog_delete_message"
    mainBtnLabel="user__dialog_delete_ok"
    @clickMainBtn="onConfirmDeleteUser()"
    @close="onCancel()"
    @before-hide="onDialogBeforeHide()"
  />

  <pn-small-dialog
    v-model="showDialogRestoreUser"
    icon="mdi-account-reactivate-outline"
    color="green"
    title="user__dialog_restore_title"
    message1="user__dialog_restore_message"
    mainBtnLabel="user__dialog_restore_ok"
    @clickMainBtn="onConfirmRestoreUser()"
  />

</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useUsersStore } from 'stores/users'
  import { useCompaniesStore } from 'stores/companies'
  import type { User } from 'types/Users'
  defineOptions({ inheritAttrs: false })

  const router = useRouter()
  const route = useRoute()
 
  const search = ref('')
  const usersStore = useUsersStore()
  const companiesStore = useCompaniesStore()

  const users = usersStore.getUsers
  const usersInit = computed(() => usersStore.isInit)

  const deleteUserId = ref<number | undefined>(undefined)
  const showDialogDeleteUser = ref<boolean>(false)
  const currentSlideEvent = ref<SlideEvent | null>(null)
  const closedByUserAction = ref(false)

  const mapUsers = computed(() => users.map(el => ({...el, ...userSection(el)})))

  interface SlideEvent {
    reset: () => void
  }

  const displayUsersAll = computed(() => {
    if (!search.value || !(search.value && search.value.trim())) return mapUsers.value
    const searchValue = search.value.trim().toLowerCase()
    const arrOut = mapUsers.value
      .filter(el =>
        el.section1.toLowerCase().includes(searchValue) ||
        el.section2_1.toLowerCase().includes(searchValue) ||
        el.section2_2.toLowerCase().includes(searchValue) ||
        el.section3.toLowerCase().includes(searchValue)
      )
    return arrOut
  })

  const displayUsers = computed(() => displayUsersAll.value.filter(el => !el.is_block))

  function userSection (user: User) {
    const tname = () => {
      return user.firstname
          ? user.lastname
            ? user.firstname + ' ' + user.lastname
            : user.firstname
          : user.lastname ?? ''
    }

    const section1 = user.fullname ?? tname()

    const section2_1 = user.fullname ? tname() : ''

    const section2_2 = user.username ?? ''

    const section3 = (
    user.company_id && companiesStore.companyById(user.company_id)
      ? companiesStore.companyById(user.company_id)?.name + ((user.role || user.department ) ? ' / ' :'')
      : '') + 
    (user.department ? user.department + (user.role ? ' / ' : '') : '') + 
    (user.role ?? '') 

    return {
      section1,
      section2_1, section2_2,
      section3
    }
  }

  async function goUserInfo (id: number) {
    await router.push({ name: 'user_info', params: { id: route.params.id, userId: id }})
  }

  function handleSlide (event: SlideEvent, id: number) {
    currentSlideEvent.value = event
    showDialogDeleteUser.value = true
    deleteUserId.value = id
  }

  function onDialogBeforeHide () {
    if (!closedByUserAction.value) {
      onCancel()
    }
    closedByUserAction.value = false
  }

  function onCancel() {
    closedByUserAction.value = true
    if (currentSlideEvent.value) {
      currentSlideEvent.value.reset()
      currentSlideEvent.value = null
    }
  }

  async function onConfirmDeleteUser() {
    closedByUserAction.value = true
    if (deleteUserId.value) {
      await usersStore.blockUser(deleteUserId.value)
    }
    currentSlideEvent.value = null
  }

  const showBlockedUsers = ref(false)
  const blockedUsers = computed(() => displayUsersAll.value.filter(el => el.is_block))
  const unblockUserId = ref<number | undefined> (undefined)
  const showDialogRestoreUser = ref(false)

  function handleUnblockUser (id: number) {
    showDialogRestoreUser.value = true
    unblockUserId.value = id
  }

  async function onConfirmRestoreUser () {
    if (unblockUserId.value) await usersStore.restore(unblockUserId.value)
  }

  watch(showDialogRestoreUser, (newD :boolean) => {
    if (!newD) unblockUserId.value = undefined
  })

  

</script>

<style>
</style>
