<template>
  <MetaHead>
    <title>Создание QR-кода — НаСвязи</title>
    <meta
      name="description"
      content="Создайте свой QR-код для безопасного и конфиденциального взаимодействия"
    />
  </MetaHead>

  <div class="max-w-prose mx-auto py-6 px-4 md:px-6">
    <section class="content">
      <div class="max-w-prose mx-auto py-8">
        <CreateSectionManager
          :placement="placement"
          :selectedActions="selectedActions"
          :messageDeliveryMethod="messageDeliveryMethod"
        >
          <template #placement>
            <CreatePlacementSection v-model="placement" />
          </template>

          <template #actions>
            <CreateActionsSection v-model="selectedActions" />
          </template>

          <template #delivery>
            <CreateMessageDeliveryMethodSection v-model="messageDeliveryMethod" />
          </template>

          <template #messages>
            <CreatePredefinedMessagesSection :placement v-model="messages" />
          </template>

          <template #summary>
            <CreateSummarySection
              v-model:name="name"
              buttonLabel="Создать QR‑код"
              :isPending
              @nextStep="createQrCode"
            />
          </template>
        </CreateSectionManager>

        <p v-if="isError" class="text-red-500 mt-4">Ошибка создания QR‑кода: {{ error }}</p>

        <div class="h-[30dvh] md:h-[10dvh] overflow-hidden"></div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { createQrCodeDocument } from '@/api/qrCode'
import type { QRCodeDocument } from '@hereconnect/types'
import { ROUTE_NAMES } from '@/constants/routes'
import { useMutation } from '@tanstack/vue-query'

const placement = ref<null | QRCodeDocument['placement']>(null)
const selectedActions = ref<QRCodeDocument['actions']>([])
const messageDeliveryMethod = ref<null | QRCodeDocument['messageDeliveryMethod']>(null)
const messages = ref<Exclude<QRCodeDocument['predefinedMessages'], undefined>>([])
const name = ref<QRCodeDocument['name']>('')

const router = useRouter()

const {
  isPending,
  isError,
  error,
  mutate: createQrCode,
} = useMutation({
  mutationKey: ['createQrCode'],
  mutationFn: async () => {
    const qrCodeDocument = await createQrCodeDocument({
      name: name.value,
      placement: placement.value!,
      actions: selectedActions.value,
      messageDeliveryMethod: messageDeliveryMethod.value!,
      predefinedMessages: messages.value.length > 0 ? messages.value : undefined,
    })

    await router.push({
      name: ROUTE_NAMES.MANAGE_QR_CODE_READY,
      params: { qr_code_uri: qrCodeDocument.uri },
    })
  },
})
</script>
