<template>
  <div class="max-w-lg mx-auto py-6 px-4 md:px-6">
    <section class="content">
      <div class="max-w-lg mx-auto py-8">
        <!-- Секция выбора размещения -->
        <CreateSection :isActive="activeSteps.includes('placement')">
          <CreatePlacementSection v-model="placement" />
        </CreateSection>

        <!-- Секция выбора доступных действий -->
        <CreateSection :isActive="activeSteps.includes('actions')">
          <CreateActionsSection v-model="selectedActions" />
        </CreateSection>

        <!-- Секция выбора способа доставки -->
        <CreateSection v-if="activeSteps.includes('delivery')" :isActive="true">
          <CreateMessageDeliveryMethodSection v-model="messageDeliveryMethod" />
        </CreateSection>

        <!-- Секция сообщений для отправки -->
        <CreateSection
          v-if="activeSteps.includes('messages')"
          :isActive="messageDeliveryMethod !== 'telegram'"
        >
          <CreatePredefinedMessagesSection :placement="placement" v-model="messages" />
        </CreateSection>

        <!-- Секция итогового резюме -->
        <CreateSection :isActive="activeSteps.includes('summary')">
          <CreateSummarySection
            v-model:name="name"
            buttonLabel="Создать QR‑код"
            @nextStep="createQrCode"
          />
        </CreateSection>

        <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 { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { createQrCodeDocument } from '@/api/qrCode'
import type { QRCodeDocument } from '@/types/DBDocumentTypes'

// Состояния шагов
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()

// Логика создания QR-кода
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: 'ManageQRCodeReady', params: { qr_code_uri: qrCodeDocument.uri } })
  } catch (err) {
    error.value = (err as Error).message || 'Неизвестная ошибка'
  }
}

// Функция для определения доступных шагов
const activeSteps = computed(() => {
  const steps = ['placement', 'actions', 'delivery', 'messages', 'summary'] as const
  const isStepValid = {
    placement: !!placement.value,
    actions: !!placement.value,
    delivery:
      !!placement.value &&
      selectedActions.value.length > 0 &&
      selectedActions.value.includes('sendMessage'),
    messages:
      !!messageDeliveryMethod.value && messageDeliveryMethod.value === 'webPushSubscription',
    summary:
      !!placement.value &&
      selectedActions.value.length > 0 &&
      (messageDeliveryMethod.value === 'webPushSubscription' ||
        selectedActions.value.includes('viewContactInfo')),
  }

  const active = []
  for (const step of steps) {
    if (active.length === 0 || isStepValid[step]) {
      active.push(step)
    } else {
      break
    }
  }
  return active
})
</script>
