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

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

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

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

const activeTab = computed<'balances' | 'withdrawals'>(() => (
  route.query.tab === 'withdrawals' ? 'withdrawals' : 'balances'
));

function setTab(tab: 'balances' | 'withdrawals') {
  void router.replace({
    query: {
      ...route.query,
      tab,
    },
  });
}

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

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

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);
  });
});
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Бонусы"
      :search-placeholder="activeTab === 'balances' ? 'Клиент, связанный клиент, email или процент' : 'Пользователь, сумма или статус'"
    >
      <template #controls>
        <NuxtLink to="/bonus-system/referrals/new" class="btn btn-primary border-0">
          Добавить связь
        </NuxtLink>
      </template>

      <template #tabs>
        <div class="tabs tabs-boxed w-fit bg-white">
          <button
            class="tab"
            :class="{ 'tab-active': activeTab === 'balances' }"
            @click="setTab('balances')"
          >
            Балансы
          </button>
          <button
            class="tab"
            :class="{ 'tab-active': activeTab === 'withdrawals' }"
            @click="setTab('withdrawals')"
          >
            Заявки на выплату
          </button>
        </div>
      </template>
    </UiSectionSearchHero>

    <template v-if="activeTab === 'balances'">
      <div v-if="balancesQuery.loading.value || referralLinksQuery.loading.value" class="manager-empty-state">
        Загружаем балансы...
      </div>
      <div v-else-if="filteredBalances.length === 0" class="manager-empty-state">
        Бонусных связок пока нет.
      </div>
      <div v-else class="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
        <article
          v-for="item in filteredBalances"
          :key="item.userId"
          class="surface-card rounded-3xl p-5"
        >
          <div class="space-y-1">
            <h2 class="text-lg font-bold text-[#123824]">{{ item.fullName }}</h2>
            <p class="text-sm text-[#466653]">{{ item.email }}</p>
            <p v-if="item.companyName" class="text-sm text-[#466653]">{{ item.companyName }}</p>
          </div>

          <div class="mt-4 space-y-2 text-sm text-[#355947]">
            <p>Баланс: <span class="font-semibold text-[#123824]">{{ item.balance }}</span></p>
            <p>Активных связок: <span class="font-semibold text-[#123824]">{{ referralLinksByReferrer.get(item.userId)?.length ?? 0 }}</span></p>
          </div>

          <div class="mt-4 space-y-2 rounded-2xl bg-[#f4faf6] p-4 text-sm text-[#355947]">
            <p class="font-semibold text-[#123824]">Начисление идёт с заказов:</p>
            <div
              v-for="link in referralLinksByReferrer.get(item.userId) ?? []"
              :key="link.id"
              class="rounded-2xl bg-white px-3 py-2"
            >
              <p class="font-medium text-[#123824]">{{ link.refereeName }}</p>
              <p>{{ link.refereeCompanyName || link.refereeEmail }}</p>
              <p class="text-xs text-[#5c7b69]">Бонус: {{ link.bonusPercent }}%</p>
            </div>
          </div>
        </article>
      </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 filteredWithdrawals"
          :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>
    </template>
  </section>
</template>
