import { useMemo } from 'react';
import { useAtomValue } from 'jotai';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { mDirectAtom } from '../../../state/mDirectList';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { useOrphanRooms } from '../../../state/hooks/roomList';
import { RoomType, StateEvent } from '../../../../types/matrix/room';

export const useHomeRooms = () => {
  const mx = useMatrixClient();
  const mDirects = useAtomValue(mDirectAtom);
  const roomToParents = useAtomValue(roomToParentsAtom);
  const orphanRooms = useOrphanRooms(mx, allRoomsAtom, mDirects, roomToParents);

  // Filter out rooms that are sub-rooms of ANY room (not just orphan rooms)
  const rooms = useMemo(() => {
    const isSpaceLikeRoom = (roomId: string): boolean => {
      const room = mx.getRoom(roomId);
      if (!room) return false;

      if (typeof room.isSpaceRoom === 'function' && room.isSpaceRoom()) {
        return true;
      }

      const roomKindEvent = room.currentState.getStateEvents(StateEvent.PaarrotRoomKind, '');
      const roomKind = roomKindEvent?.getContent<{ kind?: string }>()?.kind;
      if (roomKind === 'forum_space') {
        return true;
      }

      const createEvent = room.currentState.getStateEvents(StateEvent.RoomCreate, '');
      const roomType = createEvent?.getContent<{ type?: string }>()?.type;
      return roomType === RoomType.Space || roomType === RoomType.Forum;
    };

    // Build a set of all sub-room IDs from ALL joined rooms
    const allSubRoomIds = new Set<string>();
    mx.getRooms().forEach((room) => {
      const subRoomsEvent = room.currentState.getStateEvents(StateEvent.PaarrotSubRooms, '');
      const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? [];
      subRooms.forEach((id) => allSubRoomIds.add(id));
    });

    // Return only rooms that are not sub-rooms of another room
    return orphanRooms.filter((roomId) => !allSubRoomIds.has(roomId) && !isSpaceLikeRoom(roomId));
  }, [mx, orphanRooms]);

  return rooms;
};
