<template>
  <LayoutWithTabs>
    <MetaHead>
      <title>Ваши QR-коды — НаСвязи</title>
      <meta
        name="description"
        content="Просматривайте и управляйте сообщениями, отправленными через ваш QR-код. Полная конфиденциальность и удобный интерфейс чата"
      />
    </MetaHead>

    <QueryRender :query="query">
      <template #default="{ data }">
        <div
          class="flex-1 grid grid-cols-2 sm:grid-cols-3 gap-5 place-self-center sm:place-self-start"
          v-if="data.rows.length > 0"
        >
          <QRCodeCard v-for="{ doc: qrCode } in data.rows" :key="qrCode!.uri" :qrCode="qrCode!" />
        </div>

        <div
          v-else
          class="flex-1 flex flex-col items-center place-self-center text-center text-gray-500"
        >
          <h1 class="text-2xl font-bold mb-4 text-center sm:text-left">Нет созданных QR-кодов</h1>
          <p class="mb-6">Вы можете создать их прямо сейчас!</p>
          <Button
            icon="pi pi-qrcode"
            label="Создать QR‑код"
            to="/create"
            as="router-link"
            class="p-button-lg"
          />
        </div>
      </template>

      <template #loading>
        <div class="flex-1 flex items-center place-self-center">
          <ProgressSpinner styleClass="mt-4" />
        </div>
      </template>

      <template #error="{ reload, error }">
        <div class="flex-1 flex flex-col items-center place-self-center text-center text-red-500">
          <p>Произошла ошибка при загрузке данных: {{ error.message }}</p>
          <Button label="Повторить попытку" class="p-button mt-4" @click="reload()" />
        </div>
      </template>
    </QueryRender>
  </LayoutWithTabs>
</template>

<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
import { qrCodeDbLocal, qrCodeDbRemote } from '@/api/dbs'
import { getUserUuid } from '@/utils/getUserUuid'
import { onMounted } from 'vue'
import type { QRCodeDocument } from '@hereconnect/types'

const query = useQuery({
  queryKey: ['qrCodes'],
  queryFn: () => {
    return qrCodeDbLocal.allDocs({
      include_docs: true,
      startkey: 'qr_code:',
      endkey: 'qr_code:\uffff',
    })
  },
})

let replication: PouchDB.Replication.Replication<QRCodeDocument> | null = null
onMounted(() => {
  replication = qrCodeDbLocal.replicate.from(qrCodeDbRemote, {
    live: true,
    selector: {
      type: 'qr_code',
      user_uuid: getUserUuid(),
    },
  })
  replication.on('change', () => {
    query.refetch()
  })
})
onBeforeUnmount(() => {
  if (replication) {
    replication.cancel()
  }
})
</script>
