import { useEffect, useState } from 'react';

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

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

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

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