import React, { useCallback, useContext, useEffect, useState } from "react";
import { MkdInfiniteScroll } from "@/components/MkdInfiniteScroll";
import MkdSDK from "@/utils/MkdSDK";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import { GlobalContext, showToast } from "@/context/Global";

const InfiniteScrollTest = () => {
  // NEXT Function example
  const sdk = new MkdSDK();
  const { state, dispatch: authDispatch } = useContext(AuthContext);
  const { state: globalState, dispatch: globalDispatch } =
    useContext(GlobalContext);

  const [cursorPaginateData, setCursorPaginateData] = useState([]);
  const [nextCursor, setNextCursor] = useState(0);
  const [currentcursor, setCurrentCursor] = useState(0);
  const [pageSize, setPageSize] = useState(10);

  const next = useCallback(
    (initialized, cursor) => {
      (async () => {
        try {
          sdk.setTable("user");
          const result = await sdk.callRestAPI(
            { limit: pageSize, cursor: cursor },
            "CURSORPAGINATE"
          );
          if (!result.error) {
            if (!initialized) {
              setCursorPaginateData(() => [...result?.list]);
            } else {
              setCursorPaginateData((prev) => [...prev, ...result?.list]);
            }
            setCurrentCursor(result?.cursor);
            setNextCursor(result?.nextCursor);
          }
        } catch (error) {
          // write your error logic here
          const message = error?.response?.data?.message
            ? error?.response?.data?.message
            : error?.message;
          showToast(globalDispatch, message, 4000, "error");
          tokenExpireError(authDispatch, message);
        }
      })();
    },
    [nextCursor, currentcursor, pageSize]
  );

  useEffect(() => {
    next();
  }, []);

  // Example Usage
  return (
    <MkdInfiniteScroll
      height={`100px`}
      className={`min-h-[25rem]`}
      next={next}
      pageSize={pageSize}
      currentCursor={currentcursor}
      nextCursor={nextCursor}
      setData={setCursorPaginateData}
      data={cursorPaginateData}
      setNextCursor={setNextCursor}
      setPageSize={setPageSize}
    >
      <ul>
        {cursorPaginateData.length
          ? cursorPaginateData.map((data, index) => (
              <li key={index}>
                {index + 1} {data?.last_name} {data?.first_name}
              </li>
            ))
          : null}
      </ul>
    </MkdInfiniteScroll>
  );
};

export default InfiniteScrollTest;
