import { useEffect, useRef, useState } from "react";
import { PAGE_SIZE } from "./constants";
import { useClickedPointConfig } from "../../stores/useClickedPointConfig";
import { useGetClickedPoint } from "./useGetClickedPoint";
import { useQueryClient } from "@tanstack/react-query";

export const useMergeTableData = (fullData, onPageSizeChange) => {
  const [mergedData, setMergedData] = useState();
  const [shouldLoadClickedPoint, setShouldLoadClickedPoint] = useState(false);
  const lastClickedPointId = useRef();

  const { data: clickedPointData, isLoading: isClickedPointLoading } =
    useGetClickedPoint(shouldLoadClickedPoint, () =>
      setShouldLoadClickedPoint(false)
    );

  const { clickedPointConfig } = useClickedPointConfig();

  const queryClient = useQueryClient();

  useEffect(() => {
    if (!fullData) return;

    setMergedData(fullData);
  }, [fullData]);

  // find clicked point among already loaded data - if no - fetch it
  useEffect(() => {
    if (!fullData || clickedPointConfig === null) return;

    const clickedPoint = fullData.results.find(
      (item) => item.id === clickedPointConfig.id
    );

    if (clickedPoint) {
      return;
    }

    setShouldLoadClickedPoint(true);
  }, [fullData, clickedPointConfig]);

  // merge data with clicked point
  useEffect(() => {
    if (!clickedPointData?.results?.[0]) return;

    lastClickedPointId.current = clickedPointData.results[0].id;

    onPageSizeChange(PAGE_SIZE + 1);
    setMergedData({
      count: fullData?.count + 1,
      results: [clickedPointData.results[0], ...fullData.results],
    });
  }, [clickedPointData, fullData]);

  // reset data after popup disappeared
  useEffect(() => {
    if (clickedPointConfig === null) {
      const queryKey = ["clicked-point", lastClickedPointId.current];
      queryClient.removeQueries({ queryKey });
      onPageSizeChange(PAGE_SIZE);
      setMergedData(fullData);
    }
  }, [clickedPointConfig, fullData]);

  return { data: mergedData, isClickedPointLoading };
};
