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

import { ipcChannels } from '../../../shared/ipc/contracts';
import { getDndApi } from '../dndApi';

export function useTokenGridSnapSession(): [
  boolean,
  { setEnabled: (enabled: boolean) => Promise<boolean> },
] {
  const api = getDndApi();
  const [enabled, setEnabledState] = useState(false);

  useEffect(() => {
    void api.invoke(ipcChannels.tokenGridSnap.getState, {}).then((res) => {
      setEnabledState(Boolean(res.enabled));
    });
    return api.on(ipcChannels.tokenGridSnap.stateChanged, ({ enabled: next }) => {
      setEnabledState(Boolean(next));
    });
  }, [api]);

  const setEnabled = useCallback(
    async (next: boolean) => {
      setEnabledState(next);
      const res = await api.invoke(ipcChannels.tokenGridSnap.setEnabled, { enabled: next });
      setEnabledState(Boolean(res.enabled));
      return Boolean(res.enabled);
    },
    [api],
  );

  return [enabled, { setEnabled }];
}
