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

    <div
      v-if="chats.length !== 0 || obsoleteChats.length !== 0"
      class="w100 flex justify-end q-px-md"
      >
      <q-btn
        @click="showDialogHelp = !showDialogHelp"
        flat dense no-caps rounded
        class="q-mb-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>

    <q-list 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">
                {{ getDate(item.bot_access_date) }}
              </span>
              <q-icon 
                :name="chatAccess(item.bot_access).icon"
                :color="chatAccess(item.bot_access).color"
                size="xs"
              />
            </div>

            <div class="flex items-center no-wrap text-caption">
              <!-- if chat has conference  -->
              <q-icon
                v-if="item.has_conference" 
                name="mdi-video-box"
                color="grey"
                size="xs"
                class="q-pr-xs"
              />
              
              <!-- if chat reconnect  -->
              <q-icon
                v-if="item.state === 2" 
                :name="chatState(2).icon"
                :color="chatState(2).color"
                size="xs"
                class="q-pr-xs"
              />

              <div class="flex no-wrap items-center">
                <q-icon name="mdi-account-outline"/>
                <span>{{ item.user_count }}</span>
              </div>
            </div>
          </q-item-section>
        </q-item>
      </q-slide-item>
    </q-list>

    <div
      v-if="displayObsoleteChats.length !== 0"
      class="flex column items-center w100"
      >
      <q-btn
        class="w100 rotate-icon-btn"
        color="grey"
        flat
        no-caps
        @click="showObsoleteChats = !showObsoleteChats"
        icon-right="arrow_drop_down"
        :class="{ 'rotate-icon': showObsoleteChats }"
        >
        <span class="text-caption">
          {{ !showObsoleteChats
            ? $t('chats__show_obsolete_chats') + ' (' + displayObsoleteChats.length +')'
            : $t('chats__hide_obsolete_chats')
          }}
        </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="showObsoleteChats" class="w100">
            <q-item
              v-for = "item in displayObsoleteChats"
              :key="item.id"
              class="w100 text-grey"
              >
              <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-section>
              <q-item-section side>
                <div
                  class="row no-wrap items-center"
                  v-if="item.state_date"
                  >
                  <span class="text-caption q-pr-xs">
                    {{ getDate(item.state_date) }}
                  </span>
                  <q-icon 
                    :name="chatState(item.state).icon"
                    :color="chatState(item.state).color"
                    size="xs"
                  />
                </div>
              </q-item-section>
            </q-item>
          </q-list>
        </transition>
      </div>
    </div>

    <pn-onboard-btn
      v-if="chats.length === 0 && obsoleteChats.length === 0 && chatsInit"
      icon="mdi-chat-plus-outline"
      message1="chats__onboard_msg1"
      message2="chats__onboard_msg2"
      @click="showAttachChatDialog=true; fabState=true"
    />
    <div
      class="column justify-center items-center w100"
      style="position: absolute; bottom: 0;"
      v-if="!chatsInit"
      >
      <q-linear-progress indeterminate />
    </div>
    <template #card-fab>
      <transition
        appear
        enter-active-class="animated zoomIn"
        >
        <pn-glass-btn
          type="fab"
          color="primary"
          >
          <q-btn
            @click="showAttachChatDialog = !showAttachChatDialog"
            fab unelevated
            class="shadow-t"
            icon="add"
            color="transparent"
            :disable="!tg.initData"
          />
        </pn-glass-btn>
      </transition>
    </template>

    <pn-bottom-sheet-dialog
      title="chats__attach_dialog_title"
      v-model="showAttachChatDialog"
      >
      <div class="column w100" v-if="isEnableChatAdd">

        <div
          v-for="item in fabMenu"
          :key="item.id" 
          class="column w100"
          >
          <div class="q-px-md column w100 items-center">
            <div class="flex no-wrap" :class="item.id !== 1 ? 'q-pt-lg' : ''">
              <q-icon
                size="sm"
                :name="typeDescription(item.chatType).icon"
                :color="typeDescription(item.chatType).color"
                class="q-mr-xs"
              />
              <div class="text-bold" :class="'text-' + typeDescription(item.chatType).color">
                {{ $t(item.title) }}
              </div>
            </div>

            <div class="text-caption text-center">
              {{ $t(item.description) }}
            </div>
            <div class="text-caption text-grey text-center">
              {{ $t(item.description2) }}
            </div>

            <q-badge
              v-if="item.badge"
              class="text-white q-my-sm"
              :color="item.badgeColor"
              :label=" $t(item.badge)"
              dense
            />
          </div>


         <!--  <q-item >
             <q-item-section avatar class="items-center">

              </q-item-section>
              <q-item-section>
                <q-item-label class="text-bold">
                  
                </q-item-label>
                <q-item-label class="text-caption text-grey">
                  {{ $t(item.description) }}
                </q-item-label>
                <q-item-label class="text-caption text-grey">
                  <q-badge :color="item.badgeColor">
                    {{ $t(item.badge) }}
                  </q-badge>
                </q-item-label>
              </q-item-section>
          </q-item> -->
          <div
            v-for="(btn, idx) in item.btns"
            :key="idx"
            class="column w100"
            >
            <q-item
              @click="showAttachChatDialog = false; btn.func()" 
              class="w100"
              clickable
              v-ripple
              >
              <q-item-section avatar class="items-center">
                <q-avatar
                  :color="btn.color"
                  :text-color="btn.textColor"
                  :icon="btn.icon"
                  rounded
                />
              </q-item-section>
              <q-item-section>
                <div class="column">
                  <div>
                    {{ $t(btn.title) }}
                  </div>
                  <div>
                    <q-badge
                      v-if="btn.badge"
                      :label="$t(btn.badge)"
                      :color="btn.badgeColor"
                    />
                  </div>
                </div>
              </q-item-section>
            </q-item>
          </div>
        </div>

        <div
          class="flex column items-center w100 q-pt-md"
          >
          <q-btn
            class="w100 rotate-icon-btn"
            color="grey"
            flat
            no-caps
            @click="displayHelpConnect = !displayHelpConnect"
            icon-right="arrow_drop_down"
            :class="{ 'rotate-icon': displayHelpConnect }"
            >
            <span class="text-caption">
              {{ 
                !displayHelpConnect
                  ? $t('chats__show_help_connect_chat')
                  : $t('chats__hide_help_connect_chat')
              }}
            </span>
          </q-btn>

          <div class="w100" style="overflow: hidden">    
            <transition
              appear
              enter-active-class="animated slideInDown"
              leave-active-class="animated slideOutUp"
              >
              <div v-if="displayHelpConnect" class="w100 column">
                <div
                  class="text-grey text-caption q-px-md"
                  >
                  <div>
                    {{ $t('chats__attach_help') }}
                    <span class="text-grey-7">
                      {{ ' @' + authStore.ENV?.BOT_NAME }}
                    </span>
                    :
                  </div>
                  <ul class="q-pl-md q-my-none">
                    <li>{{ $t('chats__attach_help_1') }}</li>
                    <li>{{ $t('chats__attach_help_2') }}</li>
                  </ul>
                </div>
              </div>
            </transition>
          </div>
        </div>

      </div>

      <div v-else class="w100 bg-white column q-py-md rounded-card fab-action-item">
        <q-banner class="bg-warning text-grey-9">
          <template #avatar>
            <q-icon name="mdi-alert-circle-outline"/>
          </template>
            <div class="text-weight-bold">{{ $t('chats__disable_add_chat') }}</div>
            <div class="text-caption">{{ $t('chats__disable_add_chat_description') }}</div>
        </q-banner>
      </div>
    </pn-bottom-sheet-dialog>
 
    <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-bottom-sheet-dialog
      v-model="showDialogHelp"
      title="chat__help_title"
      >
      <q-list class="q-px-md">
        <pn-chat-type-item :access="2"/>
        <pn-chat-type-item :access="1"/>
        <pn-chat-type-item :state="2"/>
        <pn-chat-type-item :state="3"/>
        <pn-chat-type-item :state="4"/>
        <pn-chat-type-item conference/>
      </q-list>
    </pn-bottom-sheet-dialog>
    <template #overlay>
       <pn-overlay v-if="showAttachChatDialog" style="z-index:1005;"/>
    </template>
  </pn-page-card>
</template>

<script setup lang="ts">
  import { ref, computed, inject } from 'vue'
  import { useAuthStore } from 'stores/auth'
  import { useChatsStore } from 'stores/chats'
  import type { WebApp } from '@twa-dev/types'
  import type { Chat, ObsoleteChat } from 'types/Chat'
  import { date } from 'quasar'
  import { useRouter, useRoute } from 'vue-router'
  import pnChatTypeItem from 'components/pnChatTypeItem.vue'
  import pnActionBar from 'components/pnActionBar.vue'
  import pnGlassBtn from 'components/pnGlassBtn.vue'
  import { chatAccess, chatState, typeDescription } from 'utils/chats'
 
  const router = useRouter()
  const route = useRoute()

  const search = ref('')
  const showAttachChatDialog = 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 authStore = useAuthStore()
  const isEnableChatAdd = computed(() => {
    if (!authStore.customer?.plan) return false
    const a = authStore.customer?.plan?.chat_limit
    if (a === null) return true
    const b = authStore.customer?.plan?.used_chats
    return a > b
  })
  
  const chats = computed(() => chatsStore.chats)
  const chatsInit = computed(() => chatsStore.isInit)

  const fabMenu = [
    {
      id: 1,
      chatType: 'full' as const,
      title: 'chats__attach_chat_title',
      description: 'chats__attach_chat_title_description',
      description2: 'chats__attach_chat_title_description2',
      badge: 'chats__attach_chat_badge',
      badgeColor: 'grey-5', 
      color: 'primary',
      btns: [
        {
          color: 'primary',
          textColor: 'white',
          icon: 'mdi-chat-plus-outline',
          title: 'chats__attach_chat',
          badge: 'chats__attach_chat_badge_btn',
          badgeColor: 'green',
          func: attachChat
        },
        {
          color: 'primary',
          textColor: 'white',
          icon: 'mdi-share-outline',
          title: 'chats__send_chat',
          func: sendChat
        }
      ]
    },
    {
      id: 2,
      chatType: 'notify' as const,
      title: 'chats__attach_chat_private_title',
      description: 'chats__attach_chat_private_title_description',
      description2: 'chats__attach_chat_private_title_description2',
      color: 'info',
      btns: [
        {
          color: 'info',
          textColor: 'white',
          icon: 'mdi-chat-plus-outline',
          title: 'chats__attach_private_chat',
          badge: 'chats__attach_chat_private_badge_btn',
          badgeColor: 'warning',
          func: attachPrivateChat
        }
      ]
    }
  ]

  const displayHelpConnect = ref(false)

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

    function BySearch (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 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)
      await authStore.updateProfile()
    }
    currentSlideEvent.value = null
  }

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

  async function sendChat () {
    const messageId = await chatsStore.shareChat('admin')
    if (messageId) tg.shareMessage(messageId)
  }

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

 function getDate (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')
  }

  const obsoleteChats = computed(() => chatsStore.obsoleteChats)
  const showObsoleteChats = ref(false)

  const displayObsoleteChats = computed(() => {
    return obsoleteChats.value
      .filter(searchChats)

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

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

<style scoped>
  /* fix mini border after slide */
  :deep(.q-slide-item__right)
  {
    align-self: center;
    height: 98%;
  }

  /* icon for obsolete btn chats */
  .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);
  }

  .fab-disabled :deep(.q-btn--fab) {
    opacity: 0.65;
  }
  
  .opacity-60 {
    opacity: 0.6;
  }
</style>
