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

const companyName = ref('');
const inn = ref('');
const contactName = ref('');
const email = ref('');
const config = useRuntimeConfig();

const registerMutation = useMutation(RegisterSelfDocument);
const meQuery = useQuery(MeDocument);
const connectionsQuery = useQuery(MyMessengerConnectionsDocument);

const message = ref('');
const messageTone = ref<'success' | 'error'>('success');

registerMutation.onDone(() => {
  message.value = 'Заявка на регистрацию отправлена менеджеру';
  messageTone.value = 'success';
});

registerMutation.onError((error) => {
  message.value = error.message;
  messageTone.value = 'error';
});

const telegramConnection = computed(() =>
  connectionsQuery.result.value?.myMessengerConnections?.find(
    (item: { type: 'TELEGRAM' | 'MAX'; isActive: boolean; channelId: string }) =>
      item.type === 'TELEGRAM' && item.isActive,
  ),
);

const maxConnection = computed(() =>
  connectionsQuery.result.value?.myMessengerConnections?.find(
    (item: { type: 'TELEGRAM' | 'MAX'; isActive: boolean; channelId: string }) =>
      item.type === 'MAX' && item.isActive,
  ),
);

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

  const payload = encodeURIComponent(`login:${accountEmail}`);
  const separator = baseUrl.includes('?') ? '&' : '?';
  return `${baseUrl}${separator}start=${payload}`;
}

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

function register() {
  message.value = '';
  registerMutation.mutate({
    input: {
      companyName: companyName.value,
      inn: inn.value || null,
      contactName: contactName.value,
      email: email.value,
    },
  });
}
</script>

<template>
  <section class="space-y-6">
    <div>
      <h1 class="text-3xl font-extrabold text-[#0f2f20]">Профиль</h1>
      <p class="mt-1 text-sm text-[#28543f]/80">Регистрация компании и подключение каналов уведомлений.</p>
    </div>

    <div class="grid gap-4 lg:grid-cols-2">
      <div class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">Самостоятельная регистрация</h2>
        <div class="mt-4 space-y-3">
          <input v-model="companyName" type="text" placeholder="Компания" class="input input-bordered w-full border-[#d0e8d8] bg-white/80">
          <input v-model="inn" type="text" placeholder="ИНН" class="input input-bordered w-full border-[#d0e8d8] bg-white/80">
          <input v-model="contactName" type="text" placeholder="Контактное лицо" class="input input-bordered w-full border-[#d0e8d8] bg-white/80">
          <input v-model="email" type="email" placeholder="Email" class="input input-bordered w-full border-[#d0e8d8] bg-white/80">
          <button class="btn w-full border-0 bg-[#139957] text-white hover:bg-[#0d854a]" :disabled="registerMutation.loading.value" @click="register">
            {{ registerMutation.loading.value ? 'Отправляем…' : 'Отправить заявку' }}
          </button>
        </div>
      </div>

      <div class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">Каналы уведомлений</h2>
        <div class="mt-4 space-y-3">
          <div class="rounded-2xl border border-[#d6ebde] bg-white/75 p-4">
            <p class="font-semibold">Telegram</p>
            <p class="text-sm opacity-80">
              {{ telegramConnection ? `Подключен: ${telegramConnection.channelId}` : 'Не подключен' }}
            </p>
            <a
              :href="telegramConnectUrl || undefined"
              target="_blank"
              rel="noopener noreferrer"
              class="btn btn-secondary mt-3 w-full"
              :class="{ 'btn-disabled pointer-events-none': !telegramConnectUrl }"
            >
              {{ telegramConnection ? 'Переподключить Telegram' : 'Подключить Telegram' }}
            </a>
          </div>

          <div class="rounded-2xl border border-[#d6ebde] bg-white/75 p-4">
            <p class="font-semibold">Max</p>
            <p class="text-sm opacity-80">
              {{ maxConnection ? `Подключен: ${maxConnection.channelId}` : 'Не подключен' }}
            </p>
            <a
              :href="maxConnectUrl || undefined"
              target="_blank"
              rel="noopener noreferrer"
              class="btn btn-accent mt-3 w-full"
              :class="{ 'btn-disabled pointer-events-none': !maxConnectUrl }"
            >
              {{ maxConnection ? 'Переподключить Max' : 'Подключить Max' }}
            </a>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="message"
      class="alert"
      :class="messageTone === 'success' ? 'alert-success' : 'alert-error'"
    >
      {{ message }}
    </div>
  </section>
</template>
