import { useCallback } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { roomMembersSheetAtom, RoomMembersSheetState } from '../roomMembersSheet';
import { mediaViewerAtom } from '../mediaViewer';
import { userRoomProfileAtom } from '../userRoomProfile';

export const useRoomMembersSheetState = (): RoomMembersSheetState | undefined =>
  useAtomValue(roomMembersSheetAtom);

type CloseCallback = () => void;
export const useCloseRoomMembersSheet = (): CloseCallback => {
  const setSheet = useSetAtom(roomMembersSheetAtom);
  return useCallback(() => setSheet(undefined), [setSheet]);
};

type OpenCallback = (roomId: string) => void;
export const useOpenRoomMembersSheet = (): OpenCallback => {
  const setSheet = useSetAtom(roomMembersSheetAtom);
  // Mutual exclusion with the other right-pane surfaces — same idiom as
  // `useOpenUserRoomProfile` clears `mediaViewerAtom`. On desktop the
  // members sheet, the user-room-profile sheet, and the media viewer
  // share the right-pane slot; only one can be visible.
  const setMediaViewer = useSetAtom(mediaViewerAtom);
  const setUserRoomProfile = useSetAtom(userRoomProfileAtom);

  return useCallback(
    (roomId: string) => {
      setMediaViewer(undefined);
      setUserRoomProfile(undefined);
      setSheet({ roomId });
    },
    [setSheet, setMediaViewer, setUserRoomProfile]
  );
};
