'use client';

import { OrderCard } from '../shared/order-card';
import { type ProfileProps } from './types';
import { useCustomerQuery, useIsMaster } from '@/hooks/api/customers';
import { useOrdersQuery } from '@/hooks/api/orders';

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

  const { data: { customer: profile } = {} } = useCustomerQuery({ telegramId });

  const { data: { orders } = {}, isLoading } = useOrdersQuery(
    {
      filters: {
        client: {
          documentId: {
            eq: isMaster ? profile?.documentId : customer?.documentId,
          },
        },
        slot: {
          master: {
            documentId: {
              eq: isMaster ? customer?.documentId : profile?.documentId,
            },
          },
        },
      },
      pagination: {
        limit: 5,
      },
    },
    Boolean(profile?.documentId) && Boolean(customer?.documentId),
  );

  if (!orders?.length || isLoading) return null;

  return (
    <div className="flex flex-col space-y-2 px-4">
      <h1 className="font-bold">Общие записи</h1>
      {orders?.map((order) => order && <OrderCard key={order.documentId} showDate {...order} />)}
    </div>
  );
}
