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

export const useUserRoomProfileState = (): UserRoomProfileState | undefined => {
  const data = useAtomValue(userRoomProfileAtom);

  return data;
};

type CloseCallback = () => void;
export const useCloseUserRoomProfile = (): CloseCallback => {
  const setUserRoomProfile = useSetAtom(userRoomProfileAtom);

  const close: CloseCallback = useCallback(() => {
    setUserRoomProfile(undefined);
  }, [setUserRoomProfile]);

  return close;
};

type OpenCallback = (
  roomId: string,
  spaceId: string | undefined,
  userId: string,
  cords: RectCords,
  position?: Position
) => void;
export const useOpenUserRoomProfile = (): OpenCallback => {
  const setUserRoomProfile = useSetAtom(userRoomProfileAtom);
  // Bidirectional mutual exclusion with the media viewer — opening
  // profile closes any open media viewer window / sheet. Mirrors the
  // clear-the-other-atom behaviour in `useOpenMediaViewer`. The media
  // viewer is a floating window (`RoomViewMediaWindow`) on desktop now,
  // but keeping them mutually exclusive avoids a profile pane fighting
  // the window for attention.
  const setMediaViewer = useSetAtom(mediaViewerAtom);
  // Symmetric mutual exclusion with the group-room members sheet — when
  // the user taps a row inside the members list, the per-user profile
  // takes over the right-pane slot. On mobile the members horseshoe
  // closes its own way; this also handles the desktop side-pane swap.
  const setRoomMembersSheet = useSetAtom(roomMembersSheetAtom);

  const open: OpenCallback = useCallback(
    (roomId, spaceId, userId, cords, position) => {
      setMediaViewer(undefined);
      setRoomMembersSheet(undefined);
      setUserRoomProfile({ roomId, spaceId, userId, cords, position });
    },
    [setUserRoomProfile, setMediaViewer, setRoomMembersSheet]
  );

  return open;
};
