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

type OrderItem = MyOrdersQuery['myOrders'][number];

const allOrders = useQuery(MyOrdersDocument);
const search = ref('');
const statusFilter = ref<'ALL' | 'WAITING' | 'ACTIVE' | 'CLOSED'>('ALL');

const ACTIVE_STATUSES = new Set(['NEW', 'MANAGER_PROCESSING', 'WAITING_DOUBLE_CONFIRM', 'CONFIRMED', 'IN_PROGRESS']);
const CLOSED_STATUSES = new Set(['COMPLETED', 'CLIENT_REJECTED', 'MANAGER_REJECTED', 'MANAGER_BLOCKED']);

function matchesFilter(order: OrderItem) {
  if (statusFilter.value === 'ALL') {
    return true;
  }
  if (statusFilter.value === 'WAITING') {
    return order.status === 'WAITING_DOUBLE_CONFIRM';
  }
  if (statusFilter.value === 'ACTIVE') {
    return ACTIVE_STATUSES.has(order.status);
  }
  return CLOSED_STATUSES.has(order.status);
}

const filteredOrders = computed(() => {
  const orders = allOrders.result.value?.myOrders ?? [];
  const normalizedSearch = search.value.trim().toLowerCase();

  return orders.filter((order) => {
    const text = [
      order.code,
      formatOrderCode(order.code),
      ...order.items.map((item) => item.productName),
    ]
      .join(' ')
      .toLowerCase();

    const matchSearch = !normalizedSearch || text.includes(normalizedSearch);
    return matchSearch && matchesFilter(order);
  });
});

const {
  canLoadMore,
  loadMore,
  loadMoreSentinel,
  remainingCount,
  visibleItems: visibleOrders,
} = useIncrementalList(filteredOrders, {
  pageSize: 24,
  resetKeys: [search, statusFilter],
});
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Мои заказы"
      search-placeholder="Номер заказа или товар"
    >
      <template #controls>
        <select
          v-model="statusFilter"
          class="w-full rounded-full border border-[#d7e9de] bg-white px-4 py-3 text-sm font-semibold text-[#123824] outline-none transition focus:border-[#139957] focus:shadow-[0_0_0_3px_rgba(19,153,87,0.12)] md:w-64"
        >
          <option value="ALL">Все заказы</option>
          <option value="WAITING">Ожидают подтверждения</option>
          <option value="ACTIVE">Активные</option>
          <option value="CLOSED">Закрытые</option>
        </select>
      </template>
    </UiSectionSearchHero>

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

    <div v-else class="space-y-3">
      <OrdersOrderSummaryCard
        v-for="order in visibleOrders"
        :key="order.id"
        :to="`/orders/${order.id}`"
        :code="order.code"
        :status="order.status"
        :created-at="order.createdAt"
        :total-price="order.totalPrice"
        :items="order.items"
      />

      <div
        v-if="canLoadMore"
        ref="loadMoreSentinel"
        class="flex justify-center pt-2"
      >
        <button class="btn btn-outline border-[#d7e9de] bg-white" @click="loadMore">
          Показать ещё {{ Math.min(remainingCount, 24) }}
        </button>
      </div>
    </div>
  </section>
</template>
