import { useState } from "react";
import { PAGE_SIZE } from "../constants";
import { useFilters } from "../../../stores/useFilters";
import { usePointSelection } from "../../../stores/usePointSelection";
import { useQuery } from "@tanstack/react-query";
import { getPoints } from "../../../api";
import { useMergeTableData } from "../useMergeTableData";
import { STATUSES } from "../../../config";

export const useInitialTableData = (page, resetPage) => {
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const { filters } = useFilters();
  const { prediction, categories, region } = filters;
  const {
    selection: { included },
  } = usePointSelection();

  const includedIds = [...included];

  const { data, isInitialLoading } = useQuery(
    ["table", page, filters, includedIds],
    async () => {
      const params = new URLSearchParams({
        page,
        page_size: pageSize,
        "prediction_current[]": prediction,
        "status[]": [STATUSES.initial],
        "categories[]": categories,
        "included[]": includedIds,
      });

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

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

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