import React from "react";
import { useEffect, useState } from "react";
import { useElementOnScreen } from "../../hooks/useElementOnScreen";
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export function InfinityLoader(props) {
  var initialObserverOptions = {
    root: null,
    rootMargin: "0px",
    threshold: 1.0
  };
  const {
    totalPages = -1,
    observerOptions,
    children,
    loadingComponent,
    showLoading = true,
    getData = () => Promise.resolve({}),
    onLoadMore = null,
    onSuccess = null,
    onError = null,
    wrapperStyles = {},
    loadingStyles = {},
    listStyles = {},
    renderItem = null,
    renderParent = props => /*#__PURE__*/_jsx("div", { ...props
    }),
    dependencies = []
  } = props;
  const {
    containerRef,
    isVisible
  } = useElementOnScreen(observerOptions || initialObserverOptions);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0); // Data fetch effect

  useEffect(() => {
    loadData(page, "add");
  }, [isVisible]); // Reload dependencies Effect

  useEffect(() => {
    setData([]);
    setPage(0);
    loadData(0, "set");
  }, [...dependencies]);

  function loadData(newPage, action = "add") {
    // if the new page to load is bigger than the total pages, do nothing
    // ignore when total pages is infinite
    if (newPage > totalPages && totalPages !== -1) return;
    setLoading(true);
    onLoadMore && onLoadMore(newPage);
    getData(newPage).then(res => {
      switch (action) {
        case "add":
          setData([...data, ...res]);
          break;

        default:
        case "set":
          setData(res);
          break;
      }

      setLoading(false);
      setPage(newPage + 1);
      onSuccess && onSuccess(res);
    }).catch(error => {
      setLoading(false);
      onError && onError(error);
    });
  }

  const baseParentStyles = {
    display: "flex",
    flexDirection: "column"
  };

  const parentChild = /*#__PURE__*/_jsxs(_Fragment, {
    children: [children, data.map((value, index) => {
      return renderItem ? renderItem(value, index) : /*#__PURE__*/_jsx("div", {
        children: JSON.stringify(value)
      });
    })]
  });

  return /*#__PURE__*/_jsxs("div", {
    style: wrapperStyles,
    children: [renderParent({
      children: parentChild,
      style: { ...baseParentStyles,
        ...listStyles
      }
    }), !loading && /*#__PURE__*/_jsx("div", {
      ref: containerRef,
      style: {
        width: "100%",
        ...loadingStyles
      }
    }), loading && showLoading && loadingComponent]
  });
}