'use client';

import { DataNotFound } from '../shared/alert';
import { OrderCard } from '../shared/order-card';
import { type ProfileProps } from './types';
import { useCustomerQuery } from '@/hooks/api/customers';
import { useOrdersInfiniteQuery } from '@/hooks/api/orders';
import { Button } from '@repo/ui/components/ui/button';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';

export function ProfileOrdersList({ telegramId }: Readonly<ProfileProps>) {
  const { data: { customer } = {} } = useCustomerQuery();
  const { data: { customer: profile } = {} } = useCustomerQuery({ telegramId });

  const {
    data: { pages } = {},
    fetchNextPage,
    hasNextPage,
    isLoading,
  } = useOrdersInfiniteQuery(
    {
      filters: {
        // Показываем все записи между текущим пользователем и профилем
        or: [
          {
            client: { documentId: { eq: customer?.documentId } },
            slot: { master: { documentId: { eq: profile?.documentId } } },
          },
          {
            client: { documentId: { eq: profile?.documentId } },
            slot: { master: { documentId: { eq: customer?.documentId } } },
          },
        ],
      },
    },
    { enabled: Boolean(profile?.documentId) && Boolean(customer?.documentId) },
  );

  const orders = pages?.flatMap((page) => page.orders) ?? [];

  return (
    <div className="flex flex-col space-y-2 px-4">
      <h1 className="font-bold">Недавние записи</h1>
      {isLoading && <LoadingSpinner />}
      {!isLoading && !orders.length ? <DataNotFound title="Записи не найдены" /> : null}
      {orders?.map((order) => order && <OrderCard key={order.documentId} showDate {...order} />)}
      {hasNextPage && (
        <Button onClick={() => fetchNextPage()} variant="ghost">
          Загрузить еще
        </Button>
      )}
    </div>
  );
}
