import {useQuery} from "@tanstack/react-query";
import {getPoints} from "../../../api";
import {useMergeTableData} from "../useMergeTableData";
import {appendFiltersInUse} from "../../../utils.js";
import {useUpdateLayerCounter} from "../../../stores/useUpdateLayerCounter.js";
import {useDzkhFilters} from "../../../stores/useDzkhFilters.js";
import { useWeatherFilter } from "../../../dzkh-features/WeatherSlider/useWeatherFilter.js";
import { CONSUMER_OPTIONS, tempMapper } from "../../../config.js";
import { useSimulateAccident } from "../../../stores/useSimulateAccident.js";

export const useTableData = (page, resetPage, pageSize, setPageSize, sort) => {
  const { filters, consumer_filter, source_filter, consumer_type, wall_material, energy_class } = useDzkhFilters();
  const { value } = useWeatherFilter();
  const { selectedSourceConfig } = useSimulateAccident()
  const t = tempMapper[value];
  const { updateCounter } = useUpdateLayerCounter();
  const {
    region,
  } = filters;

  const getParams = () => {
    const order =
      sort &&
      (sort.includes("prob") ||
      sort.includes("cooling_time") ||
      sort.includes("priority")) ?
        `${sort}_${t}` : sort;

    const params = new URLSearchParams({
      page,
      page_size: pageSize,
    });

    if (order) {
      params.append("ordering", order);
    }

    const customFilters = [];
    if (consumer_filter && source_filter) {
      const cK = consumer_filter.key + "_" + t;
      const sK = source_filter.key + "_" + t;
      const cFilter = `${cK}__gte=${consumer_filter.gt}&${cK}__lte=${consumer_filter.lt}`;
      const sFilter = `${sK}__gte=${source_filter.gt}&${sK}__lt=${source_filter.lt}`;
      customFilters.push(`(${sFilter})|(${cFilter})`);
    }

    if (selectedSourceConfig) {
      if (selectedSourceConfig.sourceId) customFilters.push(`(tp_number=${selectedSourceConfig.sourceId})`);
      if (selectedSourceConfig.dispatcherNumber) customFilters.push(`(ods_number=${selectedSourceConfig.dispatcherNumber})`);
    }

    if (customFilters.length !== 0) {
      params.append("filters", customFilters.join("&"));
    }

    if (consumer_filter && !source_filter) {
      params.append(consumer_filter.key + "_" + t + "__gt" , consumer_filter.gt)
      params.append(consumer_filter.key + "_" + t + "__lt", consumer_filter.lt)
    }
    if (source_filter && !consumer_filter) {
      params.append(source_filter.key + "_" + t + "__gt" , source_filter.gt)
      params.append(source_filter.key + "_" + t + "__lt", source_filter.lt)
    }

    return params;
  }

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

      return await getPoints(params, region, 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,
  };
};
