import React, { useEffect } from 'react';

import { range } from '../utils/range';
import { useGridlerStore } from './GridlerStore';

//The computer component does not need to be recalculated on every render, so we use React.memo to prevent unnecessary re-renders.
export const Pager = React.memo(() => {
  const [
    setState,
    getState,
    glideref,
    visiblePages,
    //_visibleArea,
    pageSize,
    loadPage,
    _loadingList,
    hasLocalData,
  ] = useGridlerStore((s) => [
    s.setState,
    s.getState,
    s._glideref,
    s._visiblePages,
    //s._visibleArea,
    s.pageSize,
    s.loadPage,

    s._loadingList,
    s.hasLocalData,
  ]);

  useEffect(() => {
    if (!glideref) {
      return;
    }
    setState('mounted', true);
  }, [setState]);

  //Maybe move this into a computer component.
  useEffect(() => {
    if (!glideref) {
      return;
    }
    // if (hasLocalData) {
    //   //using local data, no need to load pages
    //   return;
    // }
    const firstPage = Math.max(0, Math.floor(visiblePages.y / pageSize));
    const lastPage = Math.floor((visiblePages.y + visiblePages.height) / pageSize);
    //const upperPage = pageSize * firstPage;

    // console.log(
    //   'Render1',
    //   { firstPage, lastPage, upperPage },
    //   { pageSize, _visibleArea, visiblePages },
    //   glideref,

    //   _loadingList,
    //   _editData
    // );

    for (const page of range(firstPage, lastPage + 1, 1)) {
      loadPage(page).then(() => {
        const pg = getState('_page_data')?.[0] ?? {};
        setState('isEmpty', pg && pg.length > 0);
      });
    }
  }, [loadPage, pageSize, visiblePages, glideref, _loadingList, hasLocalData]);

  return <></>;
});

Pager.displayName = 'Gridler-Pager';
