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

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

type TransactionItem = ReferralStatsQuery['referralStats']['transactions'][number];
type WithdrawalItem = ReferralStatsQuery['referralStats']['pendingWithdrawals'][number];

const bonusQuery = useQuery(ReferralStatsDocument);
const search = ref('');

const transactions = computed<TransactionItem[]>(() => bonusQuery.result.value?.referralStats.transactions ?? []);
const withdrawals = computed<WithdrawalItem[]>(() => bonusQuery.result.value?.referralStats.pendingWithdrawals ?? []);

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

  return transactions.value.filter((transaction) => {
    if (!query) {
      return true;
    }

    return [
      transaction.userId,
      transaction.reason,
      transaction.orderId || '',
      String(transaction.amount),
    ]
      .join(' ')
      .toLowerCase()
      .includes(query);
  });
});
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Бонусы"
      search-placeholder="Пользователь, причина, заказ или сумма"
    />

    <div class="space-y-4">
      <div class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">Заявки на вывод</h2>

        <div v-if="bonusQuery.loading.value" class="manager-empty-state mt-4">
          Загружаем заявки...
        </div>
        <div v-else-if="withdrawals.length === 0" class="manager-empty-state mt-4">
          Активных заявок на вывод сейчас нет.
        </div>
        <div v-else class="mt-4 space-y-3">
          <article v-for="withdrawal in withdrawals" :key="withdrawal.id" class="rounded-2xl border border-[#d6ebde] bg-white px-4 py-4">
            <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.requesterId }}</p>
                <p class="text-sm text-[#355947]">Сумма: {{ withdrawal.amount }}</p>
                <p class="text-xs text-[#5c7b69]">{{ new Date(withdrawal.createdAt).toLocaleString() }}</p>
              </div>
              <div>
                <NuxtLink :to="`/bonus-system/withdrawals/${withdrawal.id}`" class="btn btn-accent btn-sm border-0">
                  Проверить вывод
                </NuxtLink>
              </div>
            </div>
          </article>
        </div>
      </div>

      <div class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">История транзакций</h2>

        <div v-if="bonusQuery.loading.value" class="manager-empty-state mt-4">
          Загружаем историю...
        </div>
        <div v-else-if="filteredTransactions.length === 0" class="manager-empty-state mt-4">
          Транзакции по текущему запросу не найдены.
        </div>
        <div v-else class="mt-4 space-y-3">
          <article v-for="transaction in filteredTransactions" :key="transaction.id" class="rounded-2xl border border-[#d6ebde] bg-white px-4 py-4">
            <div class="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
              <div class="space-y-1">
                <p class="text-sm font-semibold text-[#123824]">{{ transaction.reason }}</p>
                <p class="text-sm text-[#5c7b69]">Пользователь: {{ transaction.userId }}</p>
                <p v-if="transaction.orderId" class="text-sm text-[#5c7b69]">Заказ: {{ transaction.orderId }}</p>
                <p class="text-xs text-[#5c7b69]">{{ new Date(transaction.createdAt).toLocaleString() }}</p>
              </div>
              <div class="text-sm font-semibold text-[#123824]">
                {{ transaction.amount }}
              </div>
            </div>
          </article>
        </div>
      </div>
    </div>
  </section>
</template>
