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

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

type TransactionItem = ManagerBonusAccountQuery['managerBonusAccount']['transactions'][number];
type PendingWithdrawalItem = ManagerBonusAccountQuery['managerBonusAccount']['pendingWithdrawals'][number];

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

const bonusAccountQuery = useQuery(ManagerBonusAccountDocument, () => ({
  userId: userId.value,
}));

const bonusAccount = computed(() => bonusAccountQuery.result.value?.managerBonusAccount ?? null);
const transactions = computed<TransactionItem[]>(() => bonusAccount.value?.transactions ?? []);
const pendingWithdrawals = computed<PendingWithdrawalItem[]>(() => bonusAccount.value?.pendingWithdrawals ?? []);

function formatAmount(value: number) {
  return new Intl.NumberFormat('ru-RU', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  }).format(value);
}

function formatDateTime(value: string) {
  return new Date(value).toLocaleString('ru-RU');
}
</script>

<template>
  <section class="space-y-6">
    <NuxtLink to="/admin/bonuses/balances" class="text-sm font-semibold text-[#0d854a]">← Назад к бонусам</NuxtLink>

    <div v-if="bonusAccountQuery.loading.value" class="manager-empty-state">
      Загружаем бонусный счёт...
    </div>

    <div v-else-if="!bonusAccount" class="manager-empty-state">
      Бонусный счёт не найден.
    </div>

    <template v-else>
      <div class="space-y-4">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div class="space-y-1">
            <h1 class="text-3xl font-extrabold text-[#123824]">{{ bonusAccount.fullName }}</h1>
            <p v-if="bonusAccount.companyName || bonusAccount.email" class="text-sm text-[#5c7b69]">
              {{ bonusAccount.companyName || bonusAccount.email }}
            </p>
          </div>
          <div class="text-left sm:text-right">
            <p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#6a8a76]">Доступный бонус</p>
            <p class="mt-2 text-3xl font-black leading-none text-[#123824]">{{ formatAmount(bonusAccount.balance) }}</p>
          </div>
        </div>

        <div v-if="pendingWithdrawals.length" class="surface-card rounded-[32px] p-6">
          <p class="text-lg font-bold text-[#123824]">Выводы</p>

          <div class="mt-4 space-y-3">
            <article
              v-for="withdrawal in pendingWithdrawals"
              :key="withdrawal.id"
              class="rounded-[24px] bg-[#f6fbf8] px-4 py-4"
            >
              <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                <div class="space-y-1">
                  <p class="text-sm font-semibold text-[#123824]">{{ formatAmount(withdrawal.amount) }}</p>
                  <p class="text-sm text-[#355947]">Создано {{ formatDateTime(withdrawal.createdAt) }}</p>
                  <p v-if="withdrawal.reviewComment" class="text-sm text-[#355947]">{{ withdrawal.reviewComment }}</p>
                </div>

                <NuxtLink
                  :to="`/admin/bonuses/requests/${withdrawal.id}`"
                  class="text-sm font-semibold text-[#0d854a]"
                >
                  Проверить выплату
                </NuxtLink>
              </div>
            </article>
          </div>
        </div>

        <div class="surface-card rounded-[32px] p-6">
          <p class="text-lg font-bold text-[#123824]">Транзакции</p>

          <div v-if="transactions.length === 0" class="manager-empty-state mt-4">
            Начислений пока нет.
          </div>

          <div v-else class="mt-4 space-y-3">
            <article
              v-for="transaction in transactions"
              :key="transaction.id"
              class="rounded-[24px] bg-[#f6fbf8] px-4 py-4"
            >
              <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                <div class="space-y-1">
                  <p class="text-base font-semibold text-[#123824]">+{{ formatAmount(transaction.amount) }}</p>
                  <p class="text-sm text-[#355947]">{{ transaction.reason }}</p>
                  <p class="text-xs text-[#5c7b69]">{{ formatDateTime(transaction.createdAt) }}</p>
                </div>

                <NuxtLink
                  v-if="transaction.orderId"
                  :to="`/admin/orders/${transaction.orderId}`"
                  class="text-sm font-semibold text-[#0d854a]"
                >
                  Открыть заказ
                </NuxtLink>
              </div>
            </article>
          </div>
        </div>
      </div>
    </template>
  </section>
</template>
