import React, { useEffect } from 'react';
import { Room } from 'matrix-js-sdk';
import { useSearchParams } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useSpaceOptionally } from '../../hooks/useSpace';
import { roomToParentsAtom } from '../../state/room/roomToParents';
import { findForumRootSpace, shouldShowForumLobby } from '../../utils/room';
import { ForumSpaceShell } from '../forum/ForumSpaceShell';
import { RoomView } from './RoomView';

type ForumRoomViewProps = {
  room: Room;
  eventId?: string;
};

export function ForumRoomView({ room, eventId }: ForumRoomViewProps) {
  const mx = useMatrixClient();
  const space = useSpaceOptionally();
  const roomToParents = useAtomValue(roomToParentsAtom);
  const [, setSearchParams] = useSearchParams();

  const forumSpaceId =
    space && shouldShowForumLobby(space)
      ? space.roomId
      : findForumRootSpace(mx, room.roomId, roomToParents);

  const forumSpace = forumSpaceId ? mx.getRoom(forumSpaceId) : null;

  useEffect(() => {
    if (!eventId) return;
    setSearchParams(
      (prev) => {
        const next = new URLSearchParams(prev);
        next.set('post', eventId);
        if (!next.get('topic') && room.roomId !== forumSpaceId) {
          next.set('topic', room.roomId);
        }
        return next;
      },
      { replace: true }
    );
  }, [eventId, setSearchParams, room.roomId, forumSpaceId]);

  if (forumSpace && shouldShowForumLobby(forumSpace)) {
    return <ForumSpaceShell />;
  }

  return <RoomView room={room} eventId={eventId} />;
}
