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

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

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

const clientQuery = useQuery(RegistrationRequestsDocument, {
  status: null,
});
const reviewMutation = useMutation(ReviewRegistrationRequestDocument);

const currentClient = computed(() =>
  (clientQuery.result.value?.registrationRequests ?? []).find((item) => item.id === requestId.value),
);

async function approveRequest() {
  if (!currentClient.value) {
    return;
  }

  await reviewMutation.mutate({
    input: {
      requestId: currentClient.value.id,
      decision: 'APPROVE',
    },
  });

  await clientQuery.refetch({ status: null });
}

async function rejectRequest() {
  if (!currentClient.value) {
    return;
  }

  await reviewMutation.mutate({
    input: {
      requestId: currentClient.value.id,
      decision: 'REJECT',
      rejectionReason: 'Не хватает данных для регистрации.',
    },
  });

  await clientQuery.refetch({ status: null });
}
</script>

<template>
  <section class="space-y-6">
    <NuxtLink to="/clients" class="text-sm font-semibold text-[#0d854a]">← Назад к клиентам</NuxtLink>

    <div v-if="clientQuery.loading.value" class="manager-empty-state">
      Загружаем карточку клиента...
    </div>

    <div v-else-if="!currentClient" class="manager-empty-state">
      Карточка клиента не найдена.
    </div>

    <template v-else>
      <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
        <div class="manager-hero">
          <p class="manager-eyebrow">Клиент</p>
          <h1 class="manager-title">{{ currentClient.companyName }}</h1>
          <p class="manager-copy">Контакт: {{ currentClient.contactName }} · {{ currentClient.email }}</p>
        </div>

        <div v-if="currentClient.status === 'PENDING'" class="flex flex-wrap gap-2">
          <button class="btn btn-success border-0" @click="approveRequest">Одобрить</button>
          <button class="btn btn-error border-0" @click="rejectRequest">Отклонить</button>
        </div>
      </div>

      <div class="grid gap-4 lg:grid-cols-3">
        <div class="manager-stat-card">
          <p class="manager-stat-label">Статус</p>
          <p class="manager-stat-value text-lg">
            {{ currentClient.status === 'APPROVED' ? 'Активен' : currentClient.status === 'REJECTED' ? 'Отклонен' : 'На проверке' }}
          </p>
        </div>
        <div class="manager-stat-card">
          <p class="manager-stat-label">Дата заявки</p>
          <p class="manager-stat-value text-lg">{{ new Date(currentClient.createdAt).toLocaleDateString() }}</p>
        </div>
        <div class="manager-stat-card">
          <p class="manager-stat-label">ИНН</p>
          <p class="manager-stat-value text-lg">{{ currentClient.inn || 'Не указан' }}</p>
        </div>
      </div>

      <div class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">Информация</h2>
        <div class="mt-4 grid gap-3 md:grid-cols-2">
          <div class="manager-mini-card">
            <p class="text-xs font-semibold uppercase tracking-[0.12em] text-[#5c7b69]">Компания</p>
            <p class="mt-2 text-sm text-[#123824]">{{ currentClient.companyName }}</p>
          </div>
          <div class="manager-mini-card">
            <p class="text-xs font-semibold uppercase tracking-[0.12em] text-[#5c7b69]">Контакт</p>
            <p class="mt-2 text-sm text-[#123824]">{{ currentClient.contactName }}</p>
          </div>
          <div class="manager-mini-card">
            <p class="text-xs font-semibold uppercase tracking-[0.12em] text-[#5c7b69]">Email</p>
            <p class="mt-2 text-sm text-[#123824]">{{ currentClient.email }}</p>
          </div>
          <div class="manager-mini-card">
            <p class="text-xs font-semibold uppercase tracking-[0.12em] text-[#5c7b69]">Обновлено</p>
            <p class="mt-2 text-sm text-[#123824]">{{ new Date(currentClient.updatedAt).toLocaleString() }}</p>
          </div>
        </div>
      </div>

      <div v-if="currentClient.rejectionReason" class="surface-card rounded-3xl p-5">
        <h2 class="text-xl font-bold text-[#123824]">Причина отказа</h2>
        <p class="mt-3 text-sm text-[#a34a34]">{{ currentClient.rejectionReason }}</p>
      </div>
    </template>
  </section>
</template>
