'use client'

import { useMemo } from 'react'
import {
  useContactBooks,
  useContacts,
  useDefaultContactBookId,
} from '@/lib/api/hooks/use-contact-queries'
import { mapApiContactsToFullContacts } from '@/lib/api/contact-list-cache'

export function useContactsList(bookId?: string) {
  const defaultBookId = useDefaultContactBookId()
  const resolvedBookId = bookId ?? defaultBookId
  const booksQuery = useContactBooks()
  const { data: apiContacts, ...rest } = useContacts(resolvedBookId)
  const contacts = useMemo(
    () => mapApiContactsToFullContacts(resolvedBookId ?? '', apiContacts),
    [resolvedBookId, apiContacts],
  )
  const isLoading = booksQuery.isLoading || (!!resolvedBookId && rest.isLoading)
  const isError = booksQuery.isError || rest.isError
  const error = booksQuery.error ?? rest.error

  function refetch() {
    void booksQuery.refetch()
    void rest.refetch()
  }

  return {
    contacts,
    bookId: resolvedBookId,
    ...rest,
    isLoading,
    isError,
    error,
    refetch,
  }
}
