import React, { type PropsWithChildren, type Ref, useImperativeHandle } from 'react';

import { type GridlerRef, useGridlerStore } from './GridlerStore';

function _GridlerRefHandler(props: PropsWithChildren, ref: Ref<GridlerRef> | undefined) {
  const [setStateFN, getstate] = useGridlerStore((s) => [s.setStateFN, s.getState]);

  useImperativeHandle<GridlerRef, GridlerRef>(ref, () => {
    return {
      getGlideRef: () => {
        return getstate('_glideref');
      },
      getState: getstate,
      isEmpty: () => getstate('isEmpty'),
      refresh: async (parms?: any) => {
        const refreshCells = getstate('refreshCells');
        const loadPage = getstate('loadPage');
        loadPage?.(parms?.pageIndex ?? 0, 'all').then(() => {
          refreshCells?.();
        });
      },
      reload: async (parms?: any) => {
        const refreshCells = getstate('refreshCells');
        const loadPage = getstate('loadPage');
        loadPage?.(parms?.pageIndex ?? 0, 'all').then(() => {
          refreshCells?.();
        });
      },
      reloadRow: async (key: number | string) => {
        const refreshCells = getstate('refreshCells');
        //const loadPage = getstate('loadPage');
        const getRowIndexByKey = getstate('getRowIndexByKey');
        const rn = await getRowIndexByKey?.(String(key));
        if (rn && rn >= 0) {
          refreshCells?.(rn, rn + 1);
          //todo loadpage or row from server
        }
      },
      scrollToRow: async (key: number | string) => {
        if (key && Number(key) >= 0) {
          setStateFN('scrollToRowKey', (cv) => Number(key ?? cv));
        }
      },
      selectRow: async (key: number | string) => {
        if (key && Number(key) >= 0) {
          setStateFN('selectedRowKey', (cv) => Number(key ?? cv));
        }
      },
      setStateFN: setStateFN,
    };
  }, []);
  return <>{props.children}</>;
}

export const GridlerRefHandler = React.forwardRef(_GridlerRefHandler);
