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

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

const route = useRoute();
const withdrawalId = computed(() => String(route.params.id || ''));

const bonusQuery = useQuery(ReferralStatsDocument);
const reviewMutation = useMutation(ReviewRewardWithdrawalDocument);

const decision = ref<'APPROVE' | 'REJECT'>('APPROVE');
const reviewComment = ref('');
const reviewResult = ref('');

const currentWithdrawal = computed(() =>
  (bonusQuery.result.value?.referralStats.pendingWithdrawals ?? []).find((item) => item.id === withdrawalId.value),
);

async function reviewWithdrawal() {
  if (!currentWithdrawal.value) {
    return;
  }

  const response = await reviewMutation.mutate({
    input: {
      withdrawalId: currentWithdrawal.value.id,
      decision: decision.value,
      reviewComment: reviewComment.value || undefined,
    },
  });

  reviewResult.value = response?.data?.reviewRewardWithdrawal.status ?? '';
  await bonusQuery.refetch();
}
</script>

<template>
  <section class="space-y-6 max-w-3xl">
    <NuxtLink to="/bonus-system" class="text-sm font-semibold text-[#0d854a]">← Назад к бонусам</NuxtLink>

    <div v-if="bonusQuery.loading.value" class="manager-empty-state">
      Загружаем заявку на вывод...
    </div>

    <div v-else-if="!currentWithdrawal" class="manager-empty-state">
      Заявка на вывод не найдена.
    </div>

    <template v-else>
      <div class="manager-hero">
        <p class="manager-eyebrow">Вывод</p>
        <h1 class="manager-title">Проверка заявки на вывод</h1>
        <p class="manager-copy">Пользователь: {{ currentWithdrawal.requesterId }} · Сумма: {{ currentWithdrawal.amount }}</p>
      </div>

      <div class="surface-card rounded-3xl p-5 space-y-3">
        <label class="form-control">
          <span class="label-text">Решение</span>
          <select v-model="decision" class="select manager-field w-full">
            <option value="APPROVE">Одобрить</option>
            <option value="REJECT">Отклонить</option>
          </select>
        </label>

        <label class="form-control">
          <span class="label-text">Комментарий</span>
          <textarea v-model="reviewComment" class="textarea manager-field min-h-28 w-full" placeholder="Комментарий для заявки" />
        </label>

        <div>
          <button class="btn btn-primary border-0" @click="reviewWithdrawal">Сохранить решение</button>
        </div>
      </div>

      <div v-if="reviewResult" class="surface-card rounded-3xl p-5 text-sm text-[#123824]">
        Новый статус: <span class="font-semibold">{{ reviewResult }}</span>
      </div>
    </template>
  </section>
</template>
