import { useEffect, useReducer } from 'react';
import { MatrixEvent, Room, RoomMember, RoomMemberEvent } from 'matrix-js-sdk';
import { Membership } from '../../types/matrix/room';
import { useMatrixClient } from './useMatrixClient';
import { readPowerLevel, usePowerLevelsContext } from './usePowerLevels';

/**
 * Returns the list of members currently knocking on the room, reactively.
 * Returns an empty array if the current user lacks invite power level.
 */
export function usePendingKnocks(room: Room): RoomMember[] {
  const mx = useMatrixClient();
  const powerLevels = usePowerLevelsContext();
  const [, forceUpdate] = useReducer((n: number) => n + 1, 0);

  useEffect(() => {
    const handler = (_evt: MatrixEvent, member: RoomMember) => {
      if (member.roomId === room.roomId) forceUpdate();
    };
    mx.on(RoomMemberEvent.Membership, handler);
    return () => {
      mx.removeListener(RoomMemberEvent.Membership, handler);
    };
  }, [mx, room.roomId]);

  const myUserId = mx.getUserId();
  const myPowerLevel = readPowerLevel.user(powerLevels, myUserId ?? undefined);
  const invitePowerLevel = readPowerLevel.action(powerLevels, 'invite');
  const canApprove = myPowerLevel >= invitePowerLevel;

  return canApprove ? room.getMembersWithMembership(Membership.Knock) : [];
}
