import { useEffect, useState } from "react";
import { PAGE_SIZE } from "./constants";
import { useClickedPointConfig } from "../../stores/useClickedPointConfig";
import { useGetClickedPoint } from "./useGetClickedPoint";

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

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

  const { clickedPointConfig } = useClickedPointConfig();

  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.location_id === clickedPointConfig.id
    );

    if (clickedPoint) {
      return;
    }

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

  // merge data with clicked point
  useEffect(() => {
    if (!clickedPointData) return;

    onPageSizeChange((prevState) => prevState + 1);
    setMergedData((prevState) => {
      if (prevState) {
        return {
          ...prevState,
          count: prevState.count + 1,
          results: [clickedPointData.results[0], ...prevState.results],
        };
      }
    });
  }, [clickedPointData]);

  // reset data after popup disappeared
  useEffect(() => {
    if (clickedPointConfig === null) {
      onPageSizeChange(PAGE_SIZE);
      setMergedData(fullData);
    }
  }, [clickedPointConfig, fullData]);

  return { data: mergedData, isClickedPointLoading };
};
