<script setup lang="ts">
import { useMutation, useQuery } from '@vue/apollo-composable';
import OrderStatusBadge from '~/components/orders/OrderStatusBadge.vue';
import {
  ClientReviewOrderDocument,
  MyCurrentOrdersDocument,
  MyOrdersDocument,
} from '~/composables/graphql/generated';

const currentOrders = useQuery(MyCurrentOrdersDocument);
const allOrders = useQuery(MyOrdersDocument);
const reviewOrder = useMutation(ClientReviewOrderDocument);
const actionError = ref('');

reviewOrder.onError((error) => {
  actionError.value = error.message;
});

async function approve(orderId: string) {
  actionError.value = '';
  await reviewOrder.mutate({ orderId, decision: 'APPROVE' });
  await Promise.all([currentOrders.refetch(), allOrders.refetch()]);
}

async function reject(orderId: string) {
  actionError.value = '';
  await reviewOrder.mutate({ orderId, decision: 'REJECT' });
  await Promise.all([currentOrders.refetch(), allOrders.refetch()]);
}
</script>

<template>
  <section class="space-y-6">
    <div>
      <h1 class="text-3xl font-extrabold text-[#0f2f20]">Мои заказы</h1>
      <p class="mt-1 text-sm text-[#28543f]/80">Все заявки в широком карточном формате.</p>
    </div>

    <div v-if="actionError" class="alert alert-error">{{ actionError }}</div>

    <div class="space-y-4">
      <h2 class="text-lg font-bold text-[#123824]">Текущие</h2>
      <div v-if="currentOrders.loading.value" class="alert surface-card border-0">Загрузка...</div>
      <div v-else-if="(currentOrders.result.value?.myCurrentOrders?.length ?? 0) === 0" class="alert surface-card border-0">
        Активных заказов пока нет.
      </div>
      <div v-else class="space-y-3">
        <article
          v-for="order in currentOrders.result.value?.myCurrentOrders ?? []"
          :key="order.id"
          class="surface-card rounded-3xl p-4 md:p-5"
        >
          <div class="flex flex-wrap items-start justify-between gap-3">
            <div>
              <h3 class="text-lg font-bold text-[#123824]">{{ order.code }}</h3>
              <p class="text-xs text-[#355947]">{{ new Date(order.createdAt).toLocaleString() }}</p>
            </div>
            <div class="flex items-center gap-2">
              <OrderStatusBadge :status="order.status" />
            </div>
          </div>

          <ul class="mt-4 grid gap-2 text-sm text-[#214735]">
            <li
              v-for="item in order.items"
              :key="item.id"
              class="rounded-xl border border-[#d6ebde] bg-white/75 px-3 py-2"
            >
              {{ item.productName }} × {{ item.quantity }}
            </li>
          </ul>

          <div v-if="order.status === 'WAITING_DOUBLE_CONFIRM'" class="mt-4 flex flex-wrap gap-2">
            <button class="btn btn-sm border-0 bg-[#139957] text-white hover:bg-[#0d854a]" @click="approve(order.id)">
              Подтвердить
            </button>
            <button class="btn btn-sm border-0 bg-[#d32422] text-white hover:bg-[#b31f1d]" @click="reject(order.id)">
              Отклонить
            </button>
          </div>
        </article>
      </div>
    </div>

    <div class="space-y-4">
      <h2 class="text-lg font-bold text-[#123824]">История заказов</h2>
      <div v-if="allOrders.loading.value" class="alert surface-card border-0">Загрузка истории...</div>
      <div v-else-if="(allOrders.result.value?.myOrders?.length ?? 0) === 0" class="alert surface-card border-0">
        История заказов пока пустая.
      </div>
      <div v-else class="space-y-3">
        <article
          v-for="order in allOrders.result.value?.myOrders ?? []"
          :key="order.id"
          class="surface-card rounded-3xl p-4 md:p-5"
        >
          <div class="flex flex-wrap items-start justify-between gap-3">
            <div>
              <h3 class="text-lg font-bold text-[#123824]">{{ order.code }}</h3>
              <p class="text-xs text-[#355947]">{{ new Date(order.updatedAt).toLocaleString() }}</p>
            </div>
            <OrderStatusBadge :status="order.status" />
          </div>

          <div class="mt-4 grid gap-3 text-sm text-[#214735] md:grid-cols-2">
            <div class="rounded-xl border border-[#d6ebde] bg-white/75 px-3 py-2">
              Условия доставки: {{ order.deliveryTerms || 'ожидает обработки менеджером' }}
            </div>
            <div class="rounded-xl border border-[#d6ebde] bg-white/75 px-3 py-2">
              Итого: {{ order.totalPrice ?? 'после обработки менеджером' }}
            </div>
          </div>

          <div v-if="order.status === 'WAITING_DOUBLE_CONFIRM'" class="mt-4 flex flex-wrap gap-2">
            <button class="btn btn-sm border-0 bg-[#139957] text-white hover:bg-[#0d854a]" @click="approve(order.id)">
              Подтвердить
            </button>
            <button class="btn btn-sm border-0 bg-[#d32422] text-white hover:bg-[#b31f1d]" @click="reject(order.id)">
              Отклонить
            </button>
          </div>
        </article>
      </div>
    </div>
  </section>
</template>
