<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import {
  ManagerBonusBalancesDocument,
  ManagerReferralLinksDocument,
  ManagerUsersDocument,
  ManagerWithdrawalRequestsDocument,
  type ManagerBonusBalancesQuery,
  type ManagerReferralLinksQuery,
  type ManagerUsersQuery,
  type ManagerWithdrawalRequestsQuery,
} from '~/composables/graphql/generated';
import { messengerConnectionAvatarSrc } from '~/composables/useMessengerConnectionPresentation';

definePageMeta({
  middleware: ['manager-only'],
});

type BalanceItem = ManagerBonusBalancesQuery['managerBonusBalances'][number];
type ReferralLinkItem = ManagerReferralLinksQuery['managerReferralLinks'][number];
type ManagerUserItem = ManagerUsersQuery['managerUsers'][number];
type WithdrawalItem = ManagerWithdrawalRequestsQuery['managerWithdrawalRequests'][number];

const route = useRoute();
const search = ref('');
const balancesQuery = useQuery(ManagerBonusBalancesDocument);
const referralLinksQuery = useQuery(ManagerReferralLinksDocument);
const usersQuery = useQuery(ManagerUsersDocument);
const withdrawalsQuery = useQuery(ManagerWithdrawalRequestsDocument, {
  status: 'PENDING',
});

const activeTab = computed<'balances' | 'withdrawals' | 'manager'>(() => {
  if (route.query.tab === 'withdrawals') {
    return 'withdrawals';
  }
  if (route.query.tab === 'manager') {
    return 'manager';
  }
  return 'balances';
});

const balances = computed<BalanceItem[]>(() => balancesQuery.result.value?.managerBonusBalances ?? []);
const referralLinks = computed<ReferralLinkItem[]>(() => referralLinksQuery.result.value?.managerReferralLinks ?? []);
const users = computed<ManagerUserItem[]>(() => usersQuery.result.value?.managerUsers ?? []);
const withdrawals = computed<WithdrawalItem[]>(() => withdrawalsQuery.result.value?.managerWithdrawalRequests ?? []);

const usersById = computed(() => new Map(users.value.map((user) => [user.id, user])));

const referralLinksByReferrer = computed(() => {
  const grouped = new Map<string, ReferralLinkItem[]>();

  for (const link of referralLinks.value) {
    const existing = grouped.get(link.referrerId) ?? [];
    existing.push(link);
    grouped.set(link.referrerId, existing);
  }

  return grouped;
});

const filteredBalances = computed(() => {
  const query = search.value.trim().toLowerCase();

  return balances.value
    .filter((item) => {
      const links = referralLinksByReferrer.value.get(item.userId);

      if (!links?.length) {
        return false;
      }

      if (!query) {
        return true;
      }

      return [
        item.fullName,
        item.email,
        item.companyName || '',
        String(item.balance),
        ...links.flatMap((link) => [
          link.refereeName,
          link.refereeEmail,
          link.refereeCompanyName || '',
          String(link.bonusPercent),
        ]),
      ]
        .join(' ')
        .toLowerCase()
        .includes(query);
    })
    .slice()
    .sort((left, right) => {
      const leftLatest = referralLinksByReferrer.value.get(left.userId)?.[0]?.createdAt ?? '';
      const rightLatest = referralLinksByReferrer.value.get(right.userId)?.[0]?.createdAt ?? '';
      return rightLatest.localeCompare(leftLatest);
    });
});

const filteredWithdrawals = computed(() => {
  const query = search.value.trim().toLowerCase();

  return withdrawals.value.filter((item) => {
    if (!query) {
      return true;
    }

    return [
      item.requesterFullName,
      item.requesterEmail,
      item.companyName || '',
      String(item.amount),
      item.status,
      item.reviewComment || '',
    ]
      .join(' ')
      .toLowerCase()
      .includes(query);
  });
});

const {
  canLoadMore: canLoadMoreBalances,
  loadMore: loadMoreBalances,
  loadMoreSentinel: loadMoreBalancesSentinel,
  remainingCount: remainingBalancesCount,
  visibleItems: visibleBalances,
} = useIncrementalList(filteredBalances, {
  pageSize: 24,
  enabled: computed(() => activeTab.value === 'balances'),
  resetKeys: [search, activeTab],
});

const {
  canLoadMore: canLoadMoreWithdrawals,
  loadMore: loadMoreWithdrawals,
  loadMoreSentinel: loadMoreWithdrawalsSentinel,
  remainingCount: remainingWithdrawalsCount,
  visibleItems: visibleWithdrawals,
} = useIncrementalList(filteredWithdrawals, {
  pageSize: 24,
  enabled: computed(() => activeTab.value === 'withdrawals'),
  resetKeys: [search, activeTab],
});

function userInitials(fullName: string) {
  const parts = fullName
    .trim()
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2);

  if (!parts.length) {
    return 'FR';
  }

  return parts.map((part) => part[0]?.toUpperCase() ?? '').join('');
}

function formatAmount(value: number) {
  return new Intl.NumberFormat('ru-RU', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  }).format(value);
}
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Бонусы"
      :search-placeholder="activeTab === 'balances'
        ? 'Клиент, связанный клиент, email или процент'
        : activeTab === 'withdrawals'
          ? 'Пользователь, сумма или статус'
          : 'Сценарии для менеджера'"
    />

    <template v-if="activeTab === 'balances'">
      <div v-if="balancesQuery.loading.value || referralLinksQuery.loading.value || usersQuery.loading.value" class="manager-empty-state">
        Загружаем балансы...
      </div>
      <div v-else-if="filteredBalances.length === 0" class="manager-empty-state">
        Бонусных связок пока нет.
      </div>
      <div v-else class="space-y-4">
        <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-6">
          <UsersGridCard
            v-for="item in visibleBalances"
            :key="item.userId"
            :to="`/bonus-system/${item.userId}`"
            :full-name="item.fullName"
            :avatar-src="messengerConnectionAvatarSrc(usersById.get(item.userId)?.telegramConnection)"
            :initials="userInitials(item.fullName)"
            meta-label="Доступный бонус"
            :meta-value="formatAmount(item.balance)"
          />
        </div>

        <div
          v-if="canLoadMoreBalances"
          ref="loadMoreBalancesSentinel"
          class="flex justify-center"
        >
          <button class="btn btn-outline border-[#d7e9de] bg-white" @click="loadMoreBalances">
            Показать ещё {{ Math.min(remainingBalancesCount, 24) }}
          </button>
        </div>
      </div>
    </template>

    <template v-else-if="activeTab === 'manager'">
      <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <NuxtLink
          to="/bonus-system/referrals/new"
          class="surface-card surface-card-interactive rounded-3xl p-5"
        >
          <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Связки</p>
          <h2 class="mt-3 text-xl font-black tracking-[-0.03em] text-[#123824]">Добавить бонусную связь</h2>
          <p class="mt-2 text-sm leading-6 text-[#557562]">
            Связать клиентов карточным сценарием и задать процент бонусной программы.
          </p>
        </NuxtLink>

        <NuxtLink
          to="/bonus-system/transactions/new"
          class="surface-card surface-card-interactive rounded-3xl p-5"
        >
          <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Начисления</p>
          <h2 class="mt-3 text-xl font-black tracking-[-0.03em] text-[#123824]">Ручное начисление</h2>
          <p class="mt-2 text-sm leading-6 text-[#557562]">
            Добавить бонусную транзакцию вручную, если нужно быстро выдать бонус вне автоматического сценария.
          </p>
        </NuxtLink>

        <NuxtLink
          to="/bonus-system?tab=withdrawals"
          class="surface-card surface-card-interactive rounded-3xl p-5"
        >
          <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Выводы</p>
          <h2 class="mt-3 text-xl font-black tracking-[-0.03em] text-[#123824]">Проверить выплаты</h2>
          <p class="mt-2 text-sm leading-6 text-[#557562]">
            Открыть витрину заявок на вывод и разбирать новые обращения по карточкам.
          </p>
        </NuxtLink>

        <NuxtLink
          to="/bonus-program?entry=manager-preview"
          class="surface-card surface-card-interactive rounded-3xl bg-[#0d0d0f] p-5 text-white"
        >
          <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-white/55">Client view</p>
          <h2 class="mt-3 text-xl font-black tracking-[-0.03em] text-white">Открыть бонусный экран клиента</h2>
          <p class="mt-2 text-sm leading-6 text-white/72">
            Посмотреть, куда ведёт бонусное уведомление и как выглядит отдельный интерфейс программы.
          </p>
        </NuxtLink>
      </div>
    </template>

    <template v-else>
      <div v-if="withdrawalsQuery.loading.value" class="manager-empty-state">
        Загружаем заявки...
      </div>
      <div v-else-if="filteredWithdrawals.length === 0" class="manager-empty-state">
        Активных заявок на выплату сейчас нет.
      </div>
      <div v-else class="space-y-4">
        <article
          v-for="withdrawal in visibleWithdrawals"
          :key="withdrawal.id"
          class="surface-card rounded-3xl px-5 py-5"
        >
          <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
            <div class="space-y-1">
              <p class="text-sm font-semibold text-[#123824]">{{ withdrawal.requesterFullName }}</p>
              <p class="text-sm text-[#355947]">{{ withdrawal.requesterEmail }}</p>
              <p v-if="withdrawal.companyName" class="text-sm text-[#355947]">{{ withdrawal.companyName }}</p>
              <p class="text-sm text-[#355947]">Сумма: {{ withdrawal.amount }}</p>
              <p class="text-xs text-[#5c7b69]">{{ new Date(withdrawal.createdAt).toLocaleString() }}</p>
            </div>
            <NuxtLink :to="`/bonus-system/withdrawals/${withdrawal.id}`" class="btn btn-accent btn-sm border-0">
              Проверить выплату
            </NuxtLink>
          </div>
        </article>

        <div
          v-if="canLoadMoreWithdrawals"
          ref="loadMoreWithdrawalsSentinel"
          class="flex justify-center"
        >
          <button class="btn btn-outline border-[#d7e9de] bg-white" @click="loadMoreWithdrawals">
            Показать ещё {{ Math.min(remainingWithdrawalsCount, 24) }}
          </button>
        </div>
      </div>
    </template>
  </section>
</template>
