<template>
  <pn-page-template>
    <template #title>
      {{ $t('chat_card__title') }}
    </template>
    
    <template #card-actions>
      <q-btn
        rounded color="primary"
        class="w100"
        @click="onSubmit"
        v-if="chat"
        >
        {{ $t("chat_card__go_chat") }}
      </q-btn>
    </template>

    <div v-if="chat">
      <div class="flex column items-center q-px-md q-pb-sm">
        <pn-auto-avatar
          :img="chat.logo"
          :name="chat.name"
          size="100px"
          rounded
        />
        <div
          class="flex row items-start justify-center q-pt-md text-bold text-center"
          >
          {{ chat.name }}
        </div>
        <div
          v-if="chat.description"
          class="flex row items-start justify-center text-caption text-center text-grey"
          >
          {{ chat.description }}
        </div>
      </div>

      <div class="q-pb-sm w100">
        <pn-chat-type-item
          :access="chat.bot_access"
          :time="chat.bot_access_date"
        />
        <pn-chat-type-item
          v-if="chat.state !== 1"
          :state="chat.state"
          :time="chat.state_date ?? 0"
        />
      </div>

      <div class="q-pb-md w100">
        <q-item tag="label" v-ripple>
          <q-item-section avatar>
            <q-checkbox
              :model-value="chat?.has_conference ?? false" 
              @update:model-value="onConferenceChange"
              color="primary"
            />
          </q-item-section>
          <q-item-section>
            <q-item-label class="text-bold">
              {{ $t('chat_card__conference') }}
            </q-item-label>
            <q-item-label caption>
              {{ $t('chat_card__conference_description') }}
            </q-item-label>
          </q-item-section>
        </q-item>
      </div>

      <q-list v-if="chatUsers.length !== 0">
        <q-item-label class="text-caption text-bold q-py-none" header>
          {{ $t('chat_card__members') + ' (' + chatUsers.length +')' }}
        </q-item-label>
        <q-item
          v-for="item in chatUsers"
          :key="item.id"
          v-ripple
          clickable
          class="w100"
          @click="goUserInfo(item.id)"
          >
          <pn-user-list-item-body :item showStatus>
            <q-item-label 
              class="text-caption text-amber-10" lines="1"
              v-if="chat && chat?.owner_id === item.id"
              >
              <div class="flex items-center">
                <q-icon name="star" class="q-pr-xs"/>
                {{ $t('chat_card__owner') }}
              </div>
            </q-item-label>
          </pn-user-list-item-body>
        </q-item>
      </q-list>
    </div>
  </pn-page-template>
</template>

<script setup lang="ts">
  import { computed, inject } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useChatsStore } from 'stores/chats'
  import { useUsersStore } from 'stores/users'
  import { useCompaniesStore } from 'stores/companies'
  import { parseIntString } from 'utils/helpers'
  import { useUserSection } from 'composables/useUserSection'
  import pnChatTypeItem from 'components/pnChatTypeItem.vue'
  import pnUserListItemBody from 'components/pnUserListItemBody.vue'
  import type { WebApp } from '@twa-dev/types'

  const tg = inject('tg') as WebApp
  const router = useRouter()
  const route = useRoute()
  
  const chatsStore = useChatsStore()
  const usersStore = useUsersStore()
  const companiesStore = useCompaniesStore()
  
  const { userSection } = useUserSection()

  const chatId = computed(() => parseIntString(route.params.chatId))
  const chat = computed(() => chatId.value && chatsStore.chatById(chatId.value))

  async function onConferenceChange (val: boolean | null) {
    if (chatId.value && val !== null) {
      try {
        await chatsStore.update(chatId.value, { has_conference: val })
      } catch (e) {
        console.error(e)
      }
    }
  }

  function onSubmit () {
    if (chat.value) {
      tg.openTelegramLink(`https://t.me/c/${chat.value.telegram_id}/${chat.value.message_id}`)
    }
  }

  const chatUsers = computed(() => {
    if (!chat.value) return []
    const idSet = new Set(chat.value.users)
    return usersStore.users
      .filter(el => idSet.has(el.id))
      .map(el => ({
        ...el,
        ...userSection(el),
        companyName: el.company_id 
          ? companiesStore.companyById(el.company_id)?.name ?? null 
          : null
      }))
  })

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