import { useEffect, useState } from 'react';

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

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

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

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