import { useQuery } from "@tanstack/react-query";
import { useDbTableName, getPoints } from "../../../api";
import { useMergeTableData } from "../useMergeTableData";
import { STATUSES } from "../../../config";
import { usePendingPointsFilters } from "../../../stores/usePendingPointsFilters";
import { appendFiltersInUse } from "../../../utils.js";
import { useUpdateLayerCounter } from "../../../stores/useUpdateLayerCounter.js";

export const usePendingTableData = (page, resetPage, pageSize, setPageSize, sort) => {
  const { filters, ranges } = usePendingPointsFilters();
  const { updateCounter } = useUpdateLayerCounter();
  const {
    categories,
    region,
  } = filters;

  const dbTable = useDbTableName();

  const getParams = () => {
    const params = new URLSearchParams({
      page,
      page_size: pageSize,
      "categories[]": categories,
      ordering: sort,
    });

    appendFiltersInUse(params, filters, ranges);
    params.append("status[]", [STATUSES.pending, STATUSES.cancelled].join(","))

    return params;
  }

  const {data, isInitialLoading, isFetching} = useQuery(
    ["table", page, filters, sort, dbTable, updateCounter],
    async ({signal}) => {
      const params = getParams();

      return await getPoints(params, region, dbTable, signal);
    },
    {
      onError: (err) => {
        if (err.response.data.detail === "Неправильная страница") {
          resetPage();
        }
      },
      refetchOnWindowFocus: false
    }
  );

  const {data: mergedData, isClickedPointLoading} = useMergeTableData(
    data,
    setPageSize
  );

  return {
    data: mergedData,
    pageSize,
    isClickedPointLoading,
    isDataLoading: isInitialLoading || isFetching,
  };
};
