import { useEffect, useState } from 'react';

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

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

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

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