<script setup lang="ts">
const config = useRuntimeConfig()

interface APIBody {
    data: {
        "id": number,
        "is_bot": boolean,
        "first_name": string,
        "username": string,
    },
    status: 'success' | 'error'
}

const steps = ['get_me', 'get_user_id', 'get_bx']

const { data, pending, error, status } = await useLazyFetch<APIBody>(`${config.public.apiBase}/api/tg/get_me`, { server: false })

const step = ref<typeof steps[number]>('get_me')
const passed_step = ref<typeof steps>([])
const shown_steps = ref<typeof steps>(['get_me'])
const loading = ref<boolean>(false)
const disabled = ref<boolean>(false)

const serverData = ref<any>()
const serverData2 = ref<any>()

const passToStep = (stepName: typeof steps[number]) => {
    try {
        if (!passed_step.value.includes(step.value)) passed_step.value.push(step.value)
        if (!shown_steps.value.includes(stepName)) shown_steps.value.push(stepName)
        step.value = stepName
    } catch (error) {
        console.log(error)
    }
}

const nextStep = async () => {
    passed_step.value.push(step.value)
    if (step.value == 'get_me') {
        await retryStep('get_user_id')
        passToStep('get_user_id')
    }
    else if (step.value == 'get_user_id') {
        await retryStep('get_bx')
        passToStep('get_bx')
    }
}
const retryStep = async (stepName: typeof steps[number]) => {
    if (stepName == 'get_user_id') {
        loading.value = true
        const tg_res = await $fetch<APIBody>(`${config.public.apiBase}/api/tg/get_updates`)
        serverData.value = tg_res.data
        loading.value = false
    }
    else if (stepName == 'get_bx') {
        loading.value = true
        const bx_res = await $fetch<APIBody>(`${config.public.apiBase}/api/bx/get_users`)
        serverData2.value = bx_res.data
        loading.value = false
    }
}
</script>
<template>
    <UCard v-if="!pending && data">
        <template #header>
            Для получения уведомлений в тг при пинге в битриксе:
        </template>
        <div :class="[{ 'line-through': passed_step.includes('get_me') }]" v-if="shown_steps.includes('get_me')">
            Напишите <code class="code">/start</code> боту <NuxtLink class="text-pink-500" :external="true"
                :href="`https://t.me/${data.data.username}`" target="_blank">@{{ data.data.username }}</NuxtLink>
        </div>
        <div :class="[{ 'line-through': passed_step.includes('get_user_id') }]"
            v-if="shown_steps.includes('get_user_id') && serverData">
            Ваши данные пользователя
            <ul>
                <li>{{ [serverData[0].message.chat.first_name, serverData[0].message.chat.last_name,
                serverData[0].message.chat.username].filter(Boolean).join(' ') }}</li>
                <li>{{ serverData[0].message.chat.id }}</li>
            </ul>
        </div>
        <div :class="[{ 'line-through': passed_step.includes('get_bx') }]" v-if="shown_steps.includes('get_bx') && serverData2">
            Ваши данные в битриксе
            {{ serverData2 }}
        </div>

        <template #footer>
            <div class="flex gap-4">
                <UButton color="orange" v-if="['get_user_id'].includes(step)" @click="retryStep(step)">Ошибка в данных
                </UButton>
                <UButton :loading="loading" :disabled="disabled" @click="nextStep">Сделано</UButton>
            </div>
        </template>
    </UCard>
</template>