<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import {
  MeDocument,
  MyMessengerConnectionsDocument,
} from '~/composables/graphql/generated';
import { useMessengerStart } from '~/composables/useMessengerStart';

type MessengerItem = {
  type: 'TELEGRAM' | 'MAX';
  isActive: boolean;
  channelId: string;
};

const config = useRuntimeConfig();
const meQuery = useQuery(MeDocument);
const connectionsQuery = useQuery(MyMessengerConnectionsDocument);
const { openMessengerBot, pendingChannel } = useMessengerStart();

const telegramConnection = computed(() =>
  connectionsQuery.result.value?.myMessengerConnections?.find(
    (item: MessengerItem) => item.type === 'TELEGRAM' && item.isActive,
  ),
);

const maxConnection = computed(() =>
  connectionsQuery.result.value?.myMessengerConnections?.find(
    (item: MessengerItem) => item.type === 'MAX' && item.isActive,
  ),
);

function buildBotConnectUrl(baseUrl: string) {
  const accountEmail = meQuery.result.value?.me?.email?.trim().toLowerCase();
  if (!accountEmail || !baseUrl) {
    return '';
  }

  return baseUrl;
}

const telegramConnectUrl = computed(() => buildBotConnectUrl(config.public.telegramBotUrl || ''));
const maxConnectUrl = computed(() => buildBotConnectUrl(config.public.maxBotUrl || ''));

async function connectMessenger(channel: 'TELEGRAM' | 'MAX') {
  const baseUrl = channel === 'TELEGRAM' ? telegramConnectUrl.value : maxConnectUrl.value;
  if (!baseUrl) {
    return;
  }

  await openMessengerBot({
    channel,
    baseUrl,
  });
}
</script>

<template>
  <section class="space-y-6">
    <NuxtLink to="/profile" class="link link-hover text-sm">← Назад в профиль</NuxtLink>
    <h1 class="text-3xl font-extrabold text-[#0f2f20]">Уведомления</h1>

    <div class="surface-card rounded-3xl p-5">
      <p class="text-sm text-[#355947]">
        Подключите Telegram и Max, чтобы получать статусы заказов и важные уведомления в удобном канале.
      </p>

      <div class="mt-4 space-y-3">
        <div class="rounded-2xl bg-[#f8fbf9] p-4 transition hover:shadow-md">
          <p class="font-semibold">Telegram</p>
          <p class="text-sm opacity-80">
            {{ telegramConnection ? `Подключен: ${telegramConnection.channelId}` : 'Не подключен' }}
          </p>
          <button
            class="btn btn-secondary mt-3 w-full"
            :class="{ 'btn-disabled pointer-events-none': !telegramConnectUrl }"
            :disabled="pendingChannel === 'TELEGRAM' || !telegramConnectUrl"
            @click="connectMessenger('TELEGRAM')"
          >
            {{
              pendingChannel === 'TELEGRAM'
                ? 'Открываем Telegram…'
                : telegramConnection
                  ? 'Переподключить Telegram'
                  : 'Подключить Telegram'
            }}
          </button>
        </div>

        <div class="rounded-2xl bg-[#f8fbf9] p-4 transition hover:shadow-md">
          <p class="font-semibold">Max</p>
          <p class="text-sm opacity-80">
            {{ maxConnection ? `Подключен: ${maxConnection.channelId}` : 'Не подключен' }}
          </p>
          <button
            class="btn btn-accent mt-3 w-full"
            :class="{ 'btn-disabled pointer-events-none': !maxConnectUrl }"
            :disabled="pendingChannel === 'MAX' || !maxConnectUrl"
            @click="connectMessenger('MAX')"
          >
            {{
              pendingChannel === 'MAX'
                ? 'Открываем Max…'
                : maxConnection
                  ? 'Переподключить Max'
                  : 'Подключить Max'
            }}
          </button>
        </div>
      </div>
    </div>
  </section>
</template>
