<template>
  <pn-page-card v-bind="$attrs" @updateScrollPosition="onScroll">
    <template #card-header>
      <pn-action-bar
        v-if="users.length !== 0"
        v-model="search"
        placeholder="users__search"
        :show-calendar-btn="false"
        :show-filter-btn="false"
        :shadows="isScrolled"
      />
    </template>

    <q-list 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)"
          >
          <pn-user-list-item-body :item showStatus/>
        </q-item>
      </q-slide-item>  
    </q-list>

    <!-- LEAVE USERS SECTION -->
    <div
      v-if="leaveUsers.length!==0"
      class="flex column items-center w100"
      :class="showLeaveUsers ? 'bg-grey-12' : ''"
      >
      <q-btn
        class="w100 rotate-icon-btn"
        color="grey"
        flat
        no-caps
        @click="showLeaveUsers=!showLeaveUsers"
        icon-right="arrow_drop_down"
        :class="{ 'rotate-icon': showLeaveUsers }"
        >
        <span class="text-caption">
          {{ !showLeaveUsers
            ? $t('users__show_left_users') + ' (' + leaveUsers.length +')'
            : $t('users__hide_left_users')
          }}
        </span>
      </q-btn>

      <div class="w100" style="overflow: hidden">    
        <transition
          appear
          enter-active-class="animated slideInDown"
          leave-active-class="animated slideOutUp"
          >
          <q-list v-if="showLeaveUsers" class="w100">
            <q-item
              v-for = "item in leaveUsers"
              :key="item.id"
              class="w100 text-grey"
              >
              <pn-user-list-item-body :item/>
            </q-item>
          </q-list>
        </transition>
      </div>
    </div>
    <!-- END LEAVE USERS SECTION -->

    <!-- BLOCKED USERS SECTION -->
    <div
      v-if="blockedUsers.length!==0"
      class="flex column items-center w100"
      :class="showBlockedUsers ? 'bg-grey-12' : ''"
      >
      <q-btn
        class="w100 rotate-icon-btn"
        color="grey"
        flat
        no-caps
        @click="showBlockedUsers=!showBlockedUsers"
        icon-right="arrow_drop_down"
        :class="{ 'rotate-icon': showBlockedUsers }"
        >
        <span class="text-caption">
          {{ !showBlockedUsers
            ? $t('users__show_blocked_users') + ' (' + blockedUsers.length +')'
            : $t('users__hide_blocked_users')
          }}
        </span>
      </q-btn>

      <div class="w100" style="overflow: hidden">    
        <transition
          appear
          enter-active-class="animated slideInDown"
          leave-active-class="animated slideOutUp"
          >
          <q-list 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"
              >
              <pn-user-list-item-body :item/>
            </q-item>
          </q-list>
        </transition>
      </div>
    </div>
    <!-- END BLOCKED USERS SECTION -->

    <pn-onboard-btn
      v-if="users.length === 0 && usersInit"
      icon="mdi-account-outline"
      message1="users__onboard_msg1"
      message2="users__onboard_msg2"
      noBtn
    />
    <div
      class="column justify-center items-center w100"
      style="position: absolute; bottom: 0;"
      v-if="!usersInit"
      >
      <q-linear-progress indeterminate />
    </div>

    <pn-small-dialog
      v-model="showDialogBlockUser"
      icon="mdi-account-remove-outline"
      color="negative"
      title="users__dialog_block_title"
      message1="users__dialog_block_message"
      message2="users__dialog_block_message2"
      mainBtnLabel="users__dialog_block_ok"
      @clickMainBtn="onConfirmBlockUser()"
      @close="onCancel()"
      @before-hide="onDialogBeforeHide()"
    />

    <pn-small-dialog
      v-model="showDialogRestoreUser"
      icon="mdi-account-reactivate-outline"
      color="positive"
      title="users__dialog_restore_title"
      message1="users__dialog_restore_message"
      message2="users__dialog_restore_message2"
      mainBtnLabel="users__dialog_restore_ok"
      @clickMainBtn="onConfirmRestoreUser()"
    />

  </pn-page-card>
</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 { useUserSection } from 'composables/useUserSection'
  import pnUserListItemBody from 'components/pnUserListItemBody.vue'
  import pnActionBar from 'components/pnActionBar.vue'
  
  defineOptions({ inheritAttrs: false })

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

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

  const blockUserId = ref<number | undefined>(undefined)
  const showDialogBlockUser = ref<boolean>(false)
  const currentSlideEvent = ref<SlideEvent | null>(null)
  const closedByUserAction = ref(false)
  const { userSection } = useUserSection()

  const mapUsers = computed(() => users.value.map(el => ({
    ...el,
    ...userSection(el),
    companyName: el.company_id && companiesStore.companyById(el.company_id)
      ? companiesStore.companyById(el.company_id)?.name ?? null
      : null
  })))

  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) ||
        el.companyName && el.companyName.toLowerCase().includes(searchValue)
      )
    return arrOut
  })

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

  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
    showDialogBlockUser.value = true
    blockUserId.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 onConfirmBlockUser() {
    closedByUserAction.value = true
    if (blockUserId.value) {
      await usersStore.blockUser(blockUserId.value)
    }
    currentSlideEvent.value = null
  }

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

  const showLeaveUsers = ref(false)
  const leaveUsers = computed(() => displayUsersAll.value.filter(el => el.is_leave))

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

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

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

  const isScrolled = ref(false)
  const onScroll = (pos: number) => {
    isScrolled.value = pos > 1
  }
</script>

<style scoped>
  .rotate-icon-btn {
    transition: transform 0.3s;
  }

  .rotate-icon-btn.rotate-icon :deep(.q-icon) {
    transform: rotate(180deg);
    transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  }

  .rotate-icon-btn :deep(.q-icon) {
    transform: rotate(0deg);
    transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  }
</style>
