import React, { useEffect } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { AnimatedOutlet } from '../../../components/AnimatedOutlet';
import { CachedRooms } from '../../../features/room/CachedRooms';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useSpace } from '../../../hooks/useSpace';
import { activeRoomIdAtom } from '../../../state/activeRoom';
import { roomViewCacheAtom } from '../../../state/roomViewCache';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { getAllParents, isSpace } from '../../../utils/room';
import { settingsAtom } from '../../../state/settings';
import { useSetting } from '../../../state/hooks/settings';

/**
 * Hosts space room keep-alive OUTSIDE the room route outlet.
 */
export function SpaceRoomLayout() {
  const mx = useMatrixClient();
  const space = useSpace();
  const selectedRoomId = useSelectedRoom();
  const cache = useAtomValue(roomViewCacheAtom);
  const allRooms = useAtomValue(allRoomsAtom);
  const roomToParents = useAtomValue(roomToParentsAtom);
  const [developerTools] = useSetting(settingsAtom, 'developerTools');
  const setActiveRoomId = useSetAtom(activeRoomIdAtom);

  const room = selectedRoomId ? mx.getRoom(selectedRoomId) : undefined;
  const showingRoom = (() => {
    if (!room || !allRooms.includes(room.roomId)) return false;
    if (developerTools && isSpace(room) && room.roomId === space.roomId) return true;
    return getAllParents(roomToParents, room.roomId).has(space.roomId);
  })();
  const keepHost = showingRoom || cache.length > 0;

  useEffect(() => {
    if (!showingRoom) setActiveRoomId(undefined);
  }, [showingRoom, setActiveRoomId]);

  return (
    <div
      style={{
        flex: 1,
        minWidth: 0,
        minHeight: 0,
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {keepHost && (
        <div
          style={{
            flex: 1,
            minWidth: 0,
            minHeight: 0,
            display: showingRoom ? 'flex' : 'none',
            flexDirection: 'column',
            position: 'relative',
          }}
          aria-hidden={!showingRoom}
        >
          <CachedRooms />
        </div>
      )}
      <div
        style={{
          flex: 1,
          minWidth: 0,
          minHeight: 0,
          display: showingRoom ? 'none' : 'flex',
          flexDirection: 'column',
          position: 'relative',
        }}
      >
        <AnimatedOutlet />
      </div>
    </div>
  );
}
