'use client';

import { DataNotFound } from '../shared/alert';
import { ContactRow } from '../shared/contact-row';
import { useContactsInfiniteQuery } from '@/hooks/api/customers';
import { Button } from '@repo/ui/components/ui/button';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';

export function ContactsList() {
  const {
    data: { pages } = {},
    fetchNextPage,
    hasNextPage,
    isLoading,
  } = useContactsInfiniteQuery();

  const contacts = pages?.flatMap((page) => page.customers);

  return (
    <div className="flex flex-col space-y-2">
      {isLoading && <LoadingSpinner />}
      {!isLoading && !contacts?.length ? <DataNotFound title="Контакты не найдены" /> : null}
      {contacts?.map(
        (contact) =>
          contact && (
            <ContactRow
              description={contact.services.map((service) => service?.name).join(', ')}
              key={contact.documentId}
              {...contact}
            />
          ),
      )}
      {hasNextPage && (
        <Button onClick={() => fetchNextPage()} variant="ghost">
          Загрузить еще
        </Button>
      )}
    </div>
  );
}
