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

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

type WithdrawalItem = ManagerWithdrawalRequestsQuery['managerWithdrawalRequests'][number];

const search = ref('');
const withdrawalsQuery = useQuery(ManagerWithdrawalRequestsDocument, {
  status: 'PENDING',
});
const withdrawals = computed<WithdrawalItem[]>(() => withdrawalsQuery.result.value?.managerWithdrawalRequests ?? []);

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="Пользователь, сумма или статус"
    />

    <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>
  </section>
</template>
