<template>
  <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="placement" v-model="messages" />
          </template>

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

        <p v-if="error" 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 '@/types/DBDocumentTypes'
import { ROUTE_NAMES } from '@/constants/routes'

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 error = ref<string | null>(null)

const router = useRouter()

async function createQrCode() {
  try {
    const qrCodeDocument = await createQrCodeDocument({
      name: name.value,
      placement: placement.value!,
      actions: selectedActions.value,
      messageDeliveryMethod: messageDeliveryMethod.value!,
      predefinedMessages: messages.value.length > 0 ? messages.value : undefined,
    })

    error.value = null
    await router.push({
      name: ROUTE_NAMES.MANAGE_QR_CODE_READY,
      params: { qr_code_uri: qrCodeDocument.uri },
    })
  } catch (err) {
    error.value = (err as Error).message || 'Неизвестная ошибка'
  }
}
</script>
