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

definePageMeta({
  middleware: ['manager-only'],
  path: '/admin/bonuses/requests/:id',
  alias: ['/bonus-system/withdrawals/:id'],
});

const route = useRoute();
const withdrawalId = computed(() => String(route.params.id || ''));
type WithdrawalItem = ManagerWithdrawalRequestsQuery['managerWithdrawalRequests'][number];

const withdrawalsQuery = useQuery(ManagerWithdrawalRequestsDocument, {
  status: null,
});
const reviewMutation = useMutation(ReviewRewardWithdrawalDocument);

const reviewResult = ref('');
const isProcessed = ref(true);
const savePending = computed(() => reviewMutation.loading.value);

const currentWithdrawal = computed(() =>
  (withdrawalsQuery.result.value?.managerWithdrawalRequests ?? []).find((item: WithdrawalItem) => item.id === withdrawalId.value),
);

watch(currentWithdrawal, (withdrawal) => {
  if (!withdrawal) {
    return;
  }

  isProcessed.value = withdrawal.status !== 'REJECTED';
}, { immediate: true });

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

  const response = await reviewMutation.mutate({
    input: {
      withdrawalId: currentWithdrawal.value.id,
      decision: isProcessed.value ? 'APPROVE' : 'REJECT',
    },
  });

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

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

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

    <template v-else>
      <UiBackHeader
        to="/admin/bonuses/requests"
        back-label="Назад к бонусам"
        title="Проверка заявки на вывод"
        :subtitle="`${currentWithdrawal.requesterFullName} · ${currentWithdrawal.requesterEmail} · Сумма: ${currentWithdrawal.amount}`"
      />

      <div class="surface-card rounded-3xl p-5 md:p-6">
        <div class="space-y-5">
          <label class="flex items-start gap-4 rounded-[24px] bg-[#f5faf7] px-4 py-4">
            <input
              v-model="isProcessed"
              type="checkbox"
              class="checkbox mt-1 border-[#b9d7c5] bg-white [--chkbg:#123824] [--chkfg:#ffffff]"
            >
            <span class="space-y-1">
              <span class="block text-base font-bold text-[#123824]">Проведено</span>
              <span class="block text-sm leading-6 text-[#5c7b69]">
                Отметьте выплату как проведённую. Если галочка снята, заявка будет отклонена.
              </span>
            </span>
          </label>

          <button
            class="btn h-12 w-full rounded-full border-0 bg-[#123824] text-white shadow-[0_16px_32px_rgba(18,56,36,0.18)] hover:bg-[#0f2f20] disabled:border-0 disabled:bg-[#cfd8d2] disabled:text-[#6f8579]"
            :disabled="savePending"
            @click="reviewWithdrawal"
          >
            {{
              savePending
                ? 'Сохраняем...'
                : isProcessed
                  ? 'Провести выплату'
                  : 'Отклонить заявку'
            }}
          </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>
