import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { DealSchema, PaginationInfoSchema } from "@/lib/client";
import { getDealsOptions } from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    boardId?: number | null;
    projectId?: number | null;
    withPagination: boolean;
};

const useDealsList = ({
    withPagination,
    projectId = null,
    boardId = null,
}: Props) => {
    const [deals, setDeals] = useState<DealSchema[]>([]);
    const [page, setPage] = useState(1);
    const [paginationInfo, setPaginationInfo] = useState<PaginationInfoSchema>({
        totalPages: 1,
        totalItems: 1,
    });
    const itemsPerPage = 10;
    const queryClient = useQueryClient();

    const refetchDeals = () => {
        if (!boardId && !projectId) return;

        queryClient
            .fetchQuery({
                ...getDealsOptions({
                    query: {
                        boardId: boardId ?? null,
                        projectId: projectId ?? null,
                        page: withPagination ? page : null,
                        itemsPerPage: withPagination ? itemsPerPage : null,
                    },
                }),
            })
            .then(data => {
                setDeals(data.deals);
                setPaginationInfo(data.paginationInfo);
            })
            .catch(err => console.error(err));
    };

    useEffect(() => {
        refetchDeals();
    }, [boardId, withPagination, projectId, page]);

    return {
        deals,
        setDeals,
        refetchDeals,
        page,
        setPage,
        paginationInfo,
    };
};

export default useDealsList;
