<template>
  <div class="q-pa-none flex column col-grow no-scroll">
    <pn-scroll-list
      :hideHeader="chats.length === 0"
      >
      <template #card-body-header>
        <pn-action-bar
          v-model="search"
          placeholder="chats__search"
          :show-calendar-btn="false"
          :filter-active="showFiltersDialog"
          :filter-badge="!checkFiltersSelect"
           @open-filters="showFiltersDialog = true"
        />
      </template>

      <template #card-body-btn>
        <div class="w100 flex justify-end q-px-md">
          <q-btn
            @click="showDialogHelp = !showDialogHelp"
            flat dense no-caps
            class="q-my-xs"
            >
            <div class="text-caption flex no-wrap items-center q-px-xs text-grey">
              <span class="q-pr-xs">
                {{ $t("chats__help_chat_type") }}
              </span>
              <q-icon name="mdi-help-circle-outline" size="xs"/>
            </div>
          </q-btn>
        </div>
      </template>

      <q-list separator v-if="chats.length !== 0">
        <q-slide-item
          v-for="item in displayChats"
          :key="item.id"
          @right="handleSlide($event, item.id)"
          right-color="red"
          @click="goChatInfo(item.id)"
          >
          <template #right>
            <q-icon size="lg" name="mdi-link-off"/>
          </template>

          <q-item
            clickable
            v-ripple
            >
            <q-item-section avatar>
              <pn-auto-avatar
                :img="item.logo"
                :name="item.name"
                type="rounded"
                size="lg"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label lines="1" class="text-bold">
                {{ item.name }}
              </q-item-label>
              <q-item-label caption lines="2">
                {{ item.description }}
              </q-item-label>
            </q-item-section>
            <q-item-section side>
              <div class="row no-wrap items-center">
                <span class="text-caption q-pr-xs">
                  {{ showDate(item.bot_access_date) }}
                </span>
                <q-icon 
                  :name="getChatType(item.bot_access).icon"
                  :color="getChatType(item.bot_access).color"
                  size="xs"
                />
              </div>

              <div class="flex items-center no-wrap text-caption">
                <q-icon
                  v-if="item.restore_date"
                  :name="getChatType('reconnect').icon"
                  :color="getChatType('reconnect').color"
                  size="xs"
                  class="q-pr-sm"
                />

                <q-icon name="mdi-account-outline"/>
                <span>{{ item.user_count }}</span>
              </div>
            </q-item-section>
          </q-item>
        </q-slide-item>
      </q-list>

      <pn-onboard-btn
        v-if="chats.length === 0 && chatsInit"
        icon="mdi-chat-plus-outline"
        :message1="$t('chats__onboard_msg1')"
        :message2="$t('chats__onboard_msg2')"
        @click="showOverlay=true; fabState=true"
      />
      <div
        class="flex column justify-center items-center w100"
        style="position: absolute; bottom: 0;"
        v-if="!chatsInit"
        >
        <q-linear-progress indeterminate />
      </div>
    </pn-scroll-list>

    <q-page-sticky
      :style="{ zIndex: !showOverlay ? 'inherit' : '5100 !important' }"
      position="bottom-right"
      :offset="[0, 18]"
      class="fix-fab-offset"
      >
      <transition
        appear
        enter-active-class="animated zoomIn"
        >
        <q-fab
          v-model="fabState"
          v-if="showFab"
          icon="add"
          color="brand"
          direction="up"
          vertical-actions-align="right"
          @click="showOverlay = !showOverlay"
          :disable="!tg.initData"
          >
          <q-fab-action
            square
            clickable
            v-ripple
            class="bg-white change-fab-action q-pa-none"
            style="cursor: default"
            label-style=""
            >
            
            <template #icon>
              <q-list class="q-py-sm">
                <q-item
                  v-for="item in fabMenu"
                  :key="item.id" 
                  class="w100"
                  :clickable="item.type !== 'header'"
                  v-ripple
                  @click="item.type !== 'header' && item.func ? item?.func() : () => {}"
                  >
                  <template v-if="item.type === 'header'">
                    <div class="w100 column" :class="item.id === 4 ? 'q-pt-md' : ''">
                      <span
                        class="w100 text-center text-bold"
                        :class="'text-' + item.color"
                        style="line-height: 1rem;">
                        {{ $t(item.title) }}
                      </span>
                      <div class="text-caption text-center text-grey fab-action-item">
                        {{ $t(item.description) }}
                      </div>
                    </div>
                  </template>
                  <template v-else>
                  <q-item-section avatar class="items-center">
                    <q-avatar :color="item.color" rounded text-color="white" :icon="item.icon" />
                  </q-item-section>

                  <q-item-section class="items-start">
                      <q-item-label class="fab-action-item">
                        {{ $t(item.title) }}
                      </q-item-label>
                      <q-item-label caption class="fab-action-item text-left">
                        {{ $t(item.description) }}
                      </q-item-label>
                  </q-item-section>
                  </template>
                </q-item>
              </q-list>
            </template>
          </q-fab-action>
        </q-fab>
      </transition>
    </q-page-sticky>
  </div>

  <pn-overlay v-if="showOverlay"/>

  <pn-small-dialog
    v-model="showDialogDeleteChat"
    icon="mdi-link-off"
    color="negative"
    title="chats__dialog_unlink_title"
    message1="chats__dialog_unlink_message"
    message2="chats__dialog_unlink_message2"
    mainBtnLabel="chats__dialog_unlink_ok"
    @clickMainBtn="onConfirm()"
    @close="onCancel()"
    @before-hide="onDialogBeforeHide()"
  />

  <pn-simple-scroll-dialog
    v-model="showDialogHelp"
    title="chat__help_title"
    >
    <div class="q-py-none q-px-md q-ma-none">
      <q-list class="q-pt-sm">
        <pn-chat-type-item
          v-for="item in [0, 1, 2, 9, 10] as const"
          :key="item"
          :type="item"
          class="q-px-none"
        />
      </q-list>
      <q-separator class="q-mt-md"/>
      <div class="text-caption q-pt-md">
        {{ $t('chat_type__dialog_func_title') }}
        <ol class="q-px-md q-my-xs">
          <li>{{ $t('chat_type__dialog_func_point1') }}</li>
          <li>{{ $t('chat_type__dialog_func_point2') }}</li>
          <li>{{ $t('chat_type__dialog_func_point3') }}</li>
        </ol>
        <div class="q-pt-md">
          {{ $t('chat_type__dialog_administrator_rights')}}
        </div>
      </div>
    </div>
  </pn-simple-scroll-dialog>

  <!-- filter dialog -->
   <pn-bottom-sheet-dialog
    title="chats__filters"
    v-model="showFiltersDialog"
    >
    <template #btnSlot>
      <div>
        <q-btn
          v-if="!checkFiltersSelect"
          @click="resetFilters"
          flat
          no-caps
          dense
          color="grey-6"
          >
          {{ $t('chats__filters_reset')}}
        </q-btn>
      </div>
    </template>

    <template #footer>
      <q-btn
        rounded
        class="w100"
        color="primary"
        @click="showFiltersDialog = false"
        >
        {{$t('chats__filters_continue')}}
      </q-btn>
    </template>

    <div class="q-pl-sm text-bold text-caption">
      {{ $t('chats__filters_type') }}
    </div>
    <div class="flex column">
      <div
        v-for="(item,idx) in chatTypeOptions"
        :key="idx"
        >
        <q-checkbox
          v-model="filters.chatType"
          :val="item.value"
          >
          {{ $t(item.label) }}
        </q-checkbox>
      </div>
    </div>
  </pn-bottom-sheet-dialog>

</template>

<script setup lang="ts">
  import { ref, computed, onActivated, onDeactivated, onBeforeUnmount, inject } from 'vue'
  import { useChatsStore } from 'stores/chats'
  import type { WebApp } from '@twa-dev/types'
  import type { Chat, ChatType } from 'types/Chat'
  import { useI18n } from "vue-i18n"
  import { date } from 'quasar'
  import { useRouter, useRoute } from 'vue-router'
  import pnChatTypeItem from 'components/pnChatTypeItem.vue'
  import pnSimpleScrollDialog from 'components/pnSimpleScrollDialog.vue'
  import pnActionBar from 'components/pnActionBar.vue'
  import pnBottomSheetDialog from 'components/pnBottomSheetDialog.vue'
  import { getChatType } from 'utils/chats'
  
  const router = useRouter()
  const route = useRoute()

  const { t } = useI18n()

  const search = ref('')
  const showOverlay = ref<boolean>(false)
  const chatsStore = useChatsStore()
  const showDialogDeleteChat = ref<boolean>(false)
  const deleteChatId = ref<number | undefined>(undefined)
  const currentSlideEvent = ref<SlideEvent | null>(null)
  const closedByUserAction = ref(false)
  const showDialogHelp = ref(false)
  const tg = inject('tg') as WebApp

  const fabState = ref(false)

  interface SlideEvent {
    reset: () => void
  }

  const chats = computed(() => chatsStore.chats)
  const chatsInit = computed(() => chatsStore.isInit)

  const fabMenu = [
    { id: 1, type: 'header', title: 'chats__attach_chat_private_title', description: 'chats__attach_chat_private_title_description', color: 'info' },
    { id: 2, icon: 'mdi-chat-plus-outline', title: 'chats__attach_private_chat', description: 'chats__attach_private_chat_description', func: attachPrivateChat, color: 'info' },
    { id: 3, icon: 'mdi-share-outline', title: 'chats__send_private_chat', description: 'chats__send_private_chat_description', func: sendPrivateChat, color: 'info'},
    { id: 4, type: 'header', title: 'chats__attach_chat_title', description: 'chats__attach_chat_title_description', color: 'primary' },
    { id: 5, icon: 'mdi-chat-plus-outline', title: 'chats__attach_chat', description: 'chats__attach_chat_description', func: attachChat, color: 'primary' },
    { id: 6, icon: 'mdi-share-outline', title: 'chats__send_chat', description: 'chats__send_chat_description', func: sendChat, color: 'primary' }
  ]

  const displayChats = computed(() => {
    return chats.value
      .filter(searchChats)
      .filter(chatsType)

    function searchChats (el: Chat) {
      if (!search.value || !(search.value && search.value.trim())) return true
      const searchValue = search.value.trim().toLowerCase()
      return el.name.toLowerCase().includes(searchValue) ||
        el.description && el.description.toLowerCase().includes(searchValue)
    }

    function chatsType (el: Chat) {
      if (filters.value.chatType.length === 0) return true
      return filters.value.chatType.includes(el.bot_access)
    }
  })

  function handleSlide (event: SlideEvent, id: number) {
    currentSlideEvent.value = event
    showDialogDeleteChat.value = true
    deleteChatId.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 onConfirm() {
    closedByUserAction.value = true
    if (deleteChatId.value) {
      await chatsStore.unlink(deleteChatId.value)
    }
    currentSlideEvent.value = null
  }

  const botName = 'ready_or_not_2025_bot'
  const url = 'https://t.me/' + botName + '?startgroup='
  const urlAdminPermission='&admin=' +
  'pin_messages+' +
  'restrict_members'
  
  async function attachChat () {
    const key = await chatsStore.getKey()
    tg.openTelegramLink(url + key + urlAdminPermission)
  }

  async function sendChat () {
    const key = await chatsStore.getKey()
    const message = url + key + urlAdminPermission
    const tgShareUrl = 'https://t.me/share/url?url=' +
      encodeURIComponent( t('chats__send_chat_title')) +
      '&text=' + `${encodeURIComponent(message)}`
    tg.openTelegramLink(tgShareUrl)
  }

  async function attachPrivateChat () {
    const key = await chatsStore.getKey()
    tg.openTelegramLink(url + key)
  }

  async function sendPrivateChat () {
    const key = await chatsStore.getKey()
    const message = url + key
    const tgShareUrl = 'https://t.me/share/url?url=' +
      encodeURIComponent( t('chats__send_chat_title')) +
      '&text=' + `${encodeURIComponent(message)}`
    tg.openTelegramLink(tgShareUrl)
  }

  async function goChatInfo (chatId: number) {
    await router.push({ name: 'chat_info', params: { id: route.params.id, chatId }})
  }

  // fix fab jumping
  const showFab = ref(false)
  const timerId = ref<ReturnType<typeof setTimeout> | null>(null)

  onActivated(() => {
    timerId.value = setTimeout(() => {
      showFab.value = true
    }, 300)
  })

  onDeactivated(() => {
    showFab.value = false
    if (timerId.value) {
      clearTimeout(timerId.value)
      timerId.value = null
    }
  })

  onBeforeUnmount(() => {
    if (timerId.value) clearTimeout(timerId.value)
  })

  // filter chat
  const showFiltersDialog = ref(false)
  interface Filters {
    chatType: number[]
  }
  
  const defaultFilters = {
    chatType: []
  }
  
  const filters = ref<Filters>({ ...defaultFilters })

  const checkFiltersSelect = computed(() => (
    Object.values(filters.value).every(el => el.length === 0)
  ))

  function resetFilters() {
    (Object.keys(filters.value) as (keyof Filters)[]).forEach(key => filters.value[key] = [])
  }

  const chatTypeOptions = computed(() => {
    return [2, 1, 0, 9].map(el => ({
      id: el,
      value: el,
      label: getChatType(el as Partial<ChatType>).label
    }))
  })

 function showDate (d: number) {
    return new Date(d * 1000).getFullYear() === new Date(Date.now()).getFullYear()
    ? date.formatDate(d * 1000, 'DD MMM')
    : date.formatDate(d * 1000, 'MMM YY')
  }
   
</script>

<style scoped>
  /* width of choose element */
  .change-fab-action .q-fab__label--internal {
    max-height: none;
  }

  .change-fab-action :deep(.q-focus-helper) {
    visibility: hidden;
  }

  .q-item :deep(.q-focus-helper) {
    visibility: visible;
  }

  .change-fab-action {
    width: calc(min(100vw, var(--body-width)) - 48px) !important;
    border-radius: var(--top-radius)
  }

  .fab-action-item {
    text-wrap: auto !important; 
  }
  
  /* fix mini border after slide */
  :deep(.q-slide-item__right)
  {
    align-self: center;
    height: 98%;
  }
</style>
