<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import ruLocale from '@fullcalendar/core/locales/ru';
import {
  ManagerOrdersDocument,
  ManagerUsersDocument,
  type ManagerOrdersQuery,
  type ManagerUsersQuery,
} from '~/composables/graphql/generated';
import { messengerConnectionAvatarSrc } from '~/composables/useMessengerConnectionPresentation';

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

type ManagerOrderItem = ManagerOrdersQuery['managerOrders'][number];
type ManagerUserItem = ManagerUsersQuery['managerUsers'][number];
type StatusFilter = 'ALL' | 'NEW' | 'PRICED' | 'IN_PROGRESS' | 'CLOSED';

const route = useRoute();
const router = useRouter();

const ordersQuery = useQuery(ManagerOrdersDocument, { status: null });
const usersQuery = useQuery(ManagerUsersDocument);
const search = ref('');
const statusFilter = ref<StatusFilter>('ALL');

const viewMode = computed<'list' | 'calendar'>(() => (
  route.query.view === 'calendar'
    ? 'calendar'
    : 'list'
));

function setViewMode(view: 'list' | 'calendar') {
  void router.replace({
    query: {
      ...route.query,
      view,
    },
  });
}

const usersById = computed<Record<string, ManagerUserItem>>(() => Object.fromEntries(
  (usersQuery.result.value?.managerUsers ?? []).map((user) => [user.id, user]),
));

function customerCardMeta(customerId: string) {
  const customer = usersById.value[customerId];
  if (!customer) {
    return {
      name: customerId,
      avatarSrc: '',
      initials: customerId.slice(0, 2).toUpperCase(),
    };
  }

  return {
    name: customer.fullName,
    avatarSrc: messengerConnectionAvatarSrc(customer.telegramConnection),
    initials: customer.fullName
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((part) => part.charAt(0).toUpperCase())
      .join(''),
  };
}

function getOrderGroup(order: ManagerOrderItem) {
  if (order.status === 'NEW' || order.status === 'MANAGER_PROCESSING') {
    return 'NEW';
  }
  if (order.status === 'WAITING_DOUBLE_CONFIRM' || order.status === 'CONFIRMED') {
    return 'PRICED';
  }
  if (order.status === 'IN_PROGRESS') {
    return 'IN_PROGRESS';
  }
  return 'CLOSED';
}

function matchesFilter(order: ManagerOrderItem) {
  if (statusFilter.value === 'ALL') {
    return true;
  }
  return getOrderGroup(order) === statusFilter.value;
}

const searchedOrders = computed<ManagerOrderItem[]>(() => {
  const orders = ordersQuery.result.value?.managerOrders ?? [];
  const query = search.value.trim().toLowerCase();

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

    return !query || text.includes(query);
  });
});

const filteredOrders = computed<ManagerOrderItem[]>(() => searchedOrders.value.filter((order) => matchesFilter(order)));

const statusTabs = computed<Array<{ id: StatusFilter; label: string; count: number }>>(() => [
  {
    id: 'ALL',
    label: 'Все',
    count: searchedOrders.value.length,
  },
  {
    id: 'NEW',
    label: 'Заявки',
    count: searchedOrders.value.filter((order) => getOrderGroup(order) === 'NEW').length,
  },
  {
    id: 'PRICED',
    label: 'Предложения',
    count: searchedOrders.value.filter((order) => getOrderGroup(order) === 'PRICED').length,
  },
  {
    id: 'IN_PROGRESS',
    label: 'В работе',
    count: searchedOrders.value.filter((order) => getOrderGroup(order) === 'IN_PROGRESS').length,
  },
  {
    id: 'CLOSED',
    label: 'Закрытые',
    count: searchedOrders.value.filter((order) => getOrderGroup(order) === 'CLOSED').length,
  },
]);

const calendarOptions = computed(() => ({
  plugins: [dayGridPlugin],
  locale: ruLocale,
  initialView: 'dayGridMonth',
  height: 'auto',
  fixedWeekCount: false,
  firstDay: 1,
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: '',
  },
  buttonText: {
    today: 'Сегодня',
  },
  events: filteredOrders.value.map((order: ManagerOrderItem) => ({
    id: order.id,
    title: `${order.code} • ${order.customerId}`,
    start: new Date(order.createdAt).toISOString(),
    allDay: true,
  })),
  eventClick: ({ event }: { event: { id: string } }) => {
    void router.push(`/client-orders/${event.id}`);
  },
}));
</script>

<template>
  <section class="space-y-6">
    <UiSectionSearchHero
      v-model="search"
      title="Заказы"
      search-placeholder="Номер заказа, клиент, адрес или товар"
    >
      <template #controls>
        <div class="flex w-full flex-col gap-3 md:w-auto md:flex-row">
          <div class="inline-flex w-fit rounded-full border border-[#d7e9de] bg-white p-1">
            <button
              class="rounded-full px-4 py-2 text-sm font-semibold text-[#355947] transition"
              :class="viewMode === 'list' ? 'bg-[#123824] text-white' : 'hover:bg-[#f4faf6]'"
              @click="setViewMode('list')"
            >
              Список
            </button>
            <button
              class="rounded-full px-4 py-2 text-sm font-semibold text-[#355947] transition"
              :class="viewMode === 'calendar' ? 'bg-[#123824] text-white' : 'hover:bg-[#f4faf6]'"
              @click="setViewMode('calendar')"
            >
              Календарь
            </button>
          </div>
        </div>
      </template>

      <div class="flex flex-wrap gap-2">
        <button
          v-for="tab in statusTabs"
          :key="tab.id"
          class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-semibold transition"
          :class="statusFilter === tab.id
            ? 'border-[#0d854a] bg-[#0d854a] text-white shadow-[0_18px_38px_rgba(13,133,74,0.18)]'
            : 'border-[#d4e8da] bg-white text-[#355947] hover:border-[#b6d7c1]'"
          @click="statusFilter = tab.id"
        >
          <span>{{ tab.label }}</span>
          <span
            class="rounded-full px-2 py-0.5 text-xs"
            :class="statusFilter === tab.id ? 'bg-white/20 text-white' : 'bg-[#eef7f1] text-[#0d854a]'"
          >
            {{ tab.count }}
          </span>
        </button>
      </div>
    </UiSectionSearchHero>

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

    <div v-else-if="viewMode === 'calendar'" class="surface-card rounded-3xl p-4 md:p-5">
      <FullCalendar :options="calendarOptions" />
    </div>

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