import React, { memo, useCallback, useLayoutEffect } from 'react';
import { Box, Line } from 'folds';
import { Room as MatrixRoom } from 'matrix-js-sdk';
import { decodeRouteParam } from '../../pages/pathUtils';
import { useParams } from 'react-router-dom';
import { isKeyHotkey } from 'is-hotkey';
import { useSetAtom } from 'jotai';
import { RoomView } from './RoomView';
import { MembersDrawer } from './MembersDrawer';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { useSetting } from '../../state/hooks/settings';
import { usePeopleDrawerSetting } from '../../state/hooks/peopleDrawer';
import { settingsAtom } from '../../state/settings';
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
import { useIsDirectRoom, useRoom } from '../../hooks/useRoom';
import { useKeyDown } from '../../hooks/useKeyDown';
import { useMarkAsRead } from '../../hooks/useMarkAsRead';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRoomMembers } from '../../hooks/useRoomMembers';
import { activeRoomIdAtom } from '../../state/activeRoom';
import { isForum } from '../../utils/room';
import { ForumRoomView } from './ForumRoomView';

type RoomFrameProps = {
  room: MatrixRoom;
  eventId?: string;
  /** Optimistic shell only — no live timeline. */
  pending?: boolean;
  /**
   * Visible keep-alive slot. Drives composer mount immediately (Slate cannot
   * stay mounted in hidden rooms). Timeline ignores this via memo.
   */
  active?: boolean;
};

/** Shared room column layout used by the live room and the pending-nav shell. */
export const RoomFrame = memo(function RoomFrame({
  room,
  eventId,
  pending = false,
  active = true,
}: RoomFrameProps) {
  const mx = useMatrixClient();
  const isDirect = useIsDirectRoom();
  const [isDrawer] = usePeopleDrawerSetting(isDirect);
  const screenSize = useScreenSizeContext();
  const powerLevels = usePowerLevels(room);
  const forumRoom = isForum(room);
  // Mount whenever the account pref is on — including inactive keep-alive slots —
  // so members are already loaded when you switch rooms (no pop-in).
  const showDrawer = !pending && screenSize === ScreenSize.Desktop && isDrawer;
  const members = useRoomMembers(mx, room.roomId, showDrawer);

  return (
    <PowerLevelsContextProvider value={powerLevels}>
      <Box grow="Yes" direction="Column" style={{ minHeight: 0, minWidth: 0 }}>
        {forumRoom && !pending ? (
          <ForumRoomView room={room} eventId={eventId} />
        ) : (
          <RoomView room={room} eventId={eventId} pending={pending} active={active} />
        )}
        {showDrawer && (
          <>
            <Line variant="Background" direction="Vertical" size="300" />
            <MembersDrawer key={room.roomId} room={room} members={members} />
          </>
        )}
      </Box>
    </PowerLevelsContextProvider>
  );
});

/** Titlebar + escape-to-mark-read — only for the visible cached room. */
export function ActiveRoomEffects({ room }: { room: MatrixRoom }) {
  const mx = useMatrixClient();
  const setActiveRoomId = useSetAtom(activeRoomIdAtom);
  const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
  const markAsRead = useMarkAsRead(mx);

  useLayoutEffect(() => {
    setActiveRoomId(room.roomId);
  }, [room.roomId, setActiveRoomId]);

  useKeyDown(
    window,
    useCallback(
      (evt) => {
        if (isKeyHotkey('escape', evt)) {
          markAsRead(room.roomId, hideActivity);
        }
      },
      [markAsRead, room.roomId, hideActivity]
    )
  );

  return null;
}

/** @deprecated Prefer CachedRooms for route outlets — kept for single-room mounts. */
export function Room() {
  const { eventId: rawEventId } = useParams();
  const eventId = decodeRouteParam(rawEventId);
  const room = useRoom();

  return (
    <>
      <ActiveRoomEffects room={room} />
      <RoomFrame room={room} eventId={eventId} />
    </>
  );
}
