import { useEffect, useMemo, useState } from 'react';

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

export function useTokenPathSession(): [
  TokenPathSessionState | null,
  { dispatch: (event: TokenPathSessionEvent) => Promise<void> },
] {
  const api = getDndApi();
  const [state, setState] = useState<TokenPathSessionState | null>(null);

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

  const apiWrap = useMemo(
    () => ({
      dispatch: async (event: TokenPathSessionEvent) => {
        const res = await api.invoke(ipcChannels.tokenPathSession.dispatch, { event });
        void res;
      },
    }),
    [api],
  );

  return [state, apiWrap];
}
