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

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

type ClientCard = RegistrationRequestsQuery['registrationRequests'][number];

const clientsQuery = useQuery(RegistrationRequestsDocument, {
  status: null,
});
const search = ref('');

function statusLabel(status: ClientCard['status']) {
  if (status === 'APPROVED') {
    return 'Активен';
  }
  if (status === 'REJECTED') {
    return 'Отклонен';
  }
  return 'На проверке';
}

function statusClass(status: ClientCard['status']) {
  if (status === 'APPROVED') {
    return 'badge badge-success border-0';
  }
  if (status === 'REJECTED') {
    return 'badge badge-error border-0';
  }
  return 'badge badge-warning border-0';
}

const filteredClients = computed(() => {
  const items = clientsQuery.result.value?.registrationRequests ?? [];
  const query = search.value.trim().toLowerCase();

  return items.filter((item) => {
    if (!query) {
      return true;
    }

    return [
      item.companyName,
      item.contactName,
      item.email,
      item.inn || '',
    ]
      .join(' ')
      .toLowerCase()
      .includes(query);
  });
});
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Клиенты"
      search-placeholder="Компания, контакт, email или ИНН"
    >
      <template #controls>
        <NuxtLink to="/clients/invite" class="btn btn-primary border-0">
          Пригласить клиента
        </NuxtLink>
      </template>
    </UiSectionSearchHero>

    <div v-if="clientsQuery.loading.value" class="manager-empty-state">
      Загружаем клиентов...
    </div>
    <div v-else-if="filteredClients.length === 0" class="manager-empty-state">
      По текущему запросу карточки клиентов не найдены.
    </div>

    <div v-else class="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
      <NuxtLink
        v-for="client in filteredClients"
        :key="client.id"
        :to="`/clients/${client.id}`"
        class="surface-card rounded-3xl p-5"
      >
        <div class="flex items-start justify-between gap-3">
          <div class="space-y-1">
            <h2 class="text-lg font-bold text-[#123824]">{{ client.companyName }}</h2>
            <p class="text-sm text-[#466653]">{{ client.contactName }}</p>
          </div>
          <span :class="statusClass(client.status)">{{ statusLabel(client.status) }}</span>
        </div>

        <div class="mt-4 space-y-2 text-sm text-[#355947]">
          <p>{{ client.email }}</p>
          <p v-if="client.inn">ИНН: {{ client.inn }}</p>
          <p>{{ new Date(client.createdAt).toLocaleDateString() }}</p>
        </div>

        <p v-if="client.rejectionReason" class="mt-4 text-sm text-[#a34a34]">
          {{ client.rejectionReason }}
        </p>
      </NuxtLink>
    </div>
  </section>
</template>
