import { useEffect, useState } from 'react';

import { ipcChannels } from '../../../shared/ipc/contracts';
import type { MaterialsOverlayEvent, MaterialsOverlayState } from '../../../shared/types';
import { getDndApi } from '../dndApi';

export function useMaterialsOverlayState(): readonly [
  MaterialsOverlayState | null,
  { dispatch: (event: MaterialsOverlayEvent) => Promise<void> },
] {
  const api = getDndApi();
  const [state, setState] = useState<MaterialsOverlayState | null>(null);

  useEffect(() => {
    void api.invoke(ipcChannels.materialsOverlay.getState, {}).then((r) => {
      setState(r.state);
    });
    return api.on(ipcChannels.materialsOverlay.stateChanged, ({ state: next }) => {
      setState(next);
    });
  }, [api]);

  return [
    state,
    {
      dispatch: async (event) => {
        await api.invoke(ipcChannels.materialsOverlay.dispatch, { event });
      },
    },
  ] as const;
}
