import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { chatApi } from "../api/chat";
import type { ChatConversationListResponse } from "@paperclipai/shared";

export function useChatConversations(companyId: string | null, opts?: { search?: string }) {
  const queryClient = useQueryClient();

  const query = useInfiniteQuery({
    queryKey: ["chat", "conversations", companyId, opts?.search ?? ""],
    queryFn: ({ pageParam }) =>
      chatApi.listConversations(companyId!, { cursor: pageParam as string | undefined, search: opts?.search || undefined }),
    initialPageParam: undefined as string | undefined,
    getNextPageParam: (lastPage: ChatConversationListResponse) =>
      lastPage.hasMore ? lastPage.items.at(-1)?.updatedAt : undefined,
    enabled: !!companyId,
    placeholderData: (prev) => prev, // keepPreviousData equivalent -- prevents flicker (Pitfall 6)
  });

  const createMutation = useMutation({
    mutationFn: (data?: { title?: string }) => chatApi.createConversation(companyId!, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["chat", "conversations", companyId] });
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({
      id,
      ...data
    }: {
      id: string;
      title?: string;
      pinnedAt?: string | null;
      archivedAt?: string | null;
    }) => chatApi.updateConversation(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["chat", "conversations", companyId] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => chatApi.deleteConversation(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["chat", "conversations", companyId] });
    },
  });

  return { ...query, createMutation, updateMutation, deleteMutation };
}
