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

type MessengerItem = {
  id: string;
  type: 'TELEGRAM' | 'MAX';
  isActive: boolean;
  channelId: string;
  displayName?: string | null;
  username?: string | null;
  avatarAvailable?: boolean | null;
};

const route = useRoute();
const meQuery = useQuery(MeDocument);
const connectionsQuery = useQuery(MyMessengerConnectionsDocument);

const connectedChannel = computed(() => {
  const raw = String(route.query.connected || '').trim().toLowerCase();
  return raw === 'telegram' || raw === 'max' ? raw : 'telegram';
});

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,
  ),
);

const successConnection = computed(() =>
  connectedChannel.value === 'telegram' ? telegramConnection.value : maxConnection.value,
);

const profileName = computed(() => meQuery.result.value?.me?.fullName?.trim() || meQuery.result.value?.me?.email || 'Пользователь');
const successTitle = computed(() =>
  connectedChannel.value === 'telegram' ? 'Telegram успешно подключен' : 'MAX успешно подключен',
);
const successText = computed(() =>
  connectedChannel.value === 'telegram'
    ? 'Теперь этот Telegram привязан к вашему личному кабинету. Все важные уведомления и статусы заказов будут приходить сюда.'
    : 'Теперь этот MAX привязан к вашему личному кабинету. Все важные уведомления и статусы заказов будут приходить сюда.',
);
const successAvatarSrc = computed(() => messengerConnectionAvatarSrc(successConnection.value));
const successAvatarInitials = computed(() =>
  messengerConnectionInitials(successConnection.value, profileName.value.slice(0, 2).toUpperCase() || 'FR'),
);
const successConnectionName = computed(() => messengerConnectionName(successConnection.value));
const successConnectionHandleValue = computed(() => messengerConnectionHandle(successConnection.value));

onMounted(() => {
  void meQuery.refetch();
  void connectionsQuery.refetch();
});
</script>

<template>
  <section class="mx-auto flex min-h-[calc(100vh-4rem)] w-full max-w-4xl items-center py-8">
    <div class="surface-card w-full rounded-[2rem] border border-[#c7efd7] bg-[linear-gradient(135deg,#f6fff8_0%,#effbf4_100%)] p-6 md:p-8">
      <div class="flex flex-col gap-6">
        <div class="badge badge-success badge-outline w-fit">Успешно</div>

        <div class="flex flex-col gap-5 md:flex-row md:items-center">
          <div v-if="successAvatarSrc" class="avatar">
            <div class="h-24 w-24 rounded-full ring ring-[#c7efd7] ring-offset-4 ring-offset-white">
              <img :src="successAvatarSrc" :alt="successConnectionName">
            </div>
          </div>
          <div v-else class="avatar placeholder">
            <div class="h-24 w-24 rounded-full bg-[#123824] text-2xl font-bold text-white">
              <span>{{ successAvatarInitials }}</span>
            </div>
          </div>

          <div class="space-y-2">
            <h1 class="text-3xl font-extrabold text-[#0f2f20]">{{ successTitle }}</h1>
            <div class="flex flex-wrap items-center gap-2 text-sm text-[#355947]">
              <span class="font-semibold text-[#123824]">{{ successConnectionName }}</span>
              <span v-if="successConnectionHandleValue">{{ successConnectionHandleValue }}</span>
            </div>
            <p class="max-w-2xl text-sm leading-6 text-[#355947]">
              {{ successText }}
            </p>
          </div>
        </div>

        <div class="flex flex-col gap-3 sm:flex-row">
          <NuxtLink to="/profile/notifications" class="btn btn-primary">
            Перейти к уведомлениям
          </NuxtLink>
          <NuxtLink to="/" class="btn btn-ghost">
            Перейти в каталог
          </NuxtLink>
        </div>
      </div>
    </div>
  </section>
</template>
