<template>
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-4 text-center">Управление QR-кодами</h1>
    <QueryRender :query="query">
      <template #default="{ data }">
        <div v-if="data.rows.length > 0" class="flex flex-col gap-5">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <QRCodeCard v-for="{ doc: qrCode } in data.rows" :key="qrCode!.uri" :qrCode="qrCode!" />
          </div>
          <div class="text-center">
            <Button
              icon="pi pi-qrcode"
              label="Создать QR‑код"
              to="/create"
              as="router-link"
              class="p-button-outlined p-button-sm"
            />
          </div>
        </div>
        <div v-else class="text-center text-gray-500">
          <p>Нет созданных QR-кодов. Вы можете создать их прямо сейчас!</p>
          <Button
            icon="pi pi-qrcode"
            label="Создать QR‑код"
            to="/create"
            as="router-link"
            class="p-button-lg"
          />
        </div>
      </template>

      <template #error="{ reload }">
        <div class="text-center text-red-500">
          <p>Произошла ошибка при загрузке данных. Пожалуйста, попробуйте позже.</p>
          <Button label="Повторить попытку" class="p-button mt-4" @click="reload()" />
        </div>
      </template>

      <template #loading>
        <div class="text-center text-gray-500">
          <p>Загрузка QR-кодов...</p>
          <ProgressSpinner styleClass="mt-4" />
        </div>
      </template>
    </QueryRender>
  </div>
</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: async () => {
    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>
