import React, { ReactNode } from 'react';
import { useAtomValue } from 'jotai';
import { Navigate, useParams } from 'react-router-dom';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { JoinBeforeNavigate } from '../../../features/join-before-navigate';
import { useSearchParamsViaServers } from '../../../hooks/router/useSearchParamsViaServers';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { getChannelsRoomPath, getDirectRoomPath } from '../../pathUtils';
import { getCanonicalAliasOrRoomId } from '../../../utils/matrix';
import { getOrphanParents, guessPerfectParent, isSpace } from '../../../utils/room';

export function HomeRouteRoomProvider({ children: _children }: { children: ReactNode }) {
  const mx = useMatrixClient();
  // **Subscribe to allRoomsAtom even though we don't use the value**: cold-
  // start push opens `/home/{newRoomId}/` before /sync brings the brand-new
  // invite. On first render `mx.getRoom(roomId)` returns null, the provider
  // falls through to JoinBeforeNavigate, and JoinBeforeNavigate has no auto-
  // redirect — user is stuck staring at a RoomCard. The pre-P3c version
  // pulled `useHomeRooms()` here, which transitively read `allRoomsAtom`
  // through jotai and re-rendered when /sync populated the room. P3c removed
  // `useHomeRooms` along with the Home page; we restore the subscription
  // explicitly so the redirect re-evaluates after /sync. See plan §6.7 / §6.8
  // / round-5 review notes.
  useAtomValue(allRoomsAtom);
  // Subscribe roomToParentsAtom so the channels-vs-direct branch re-evaluates
  // after /sync populates the m.space.parent / m.space.child mappings. Without
  // this subscription a cold push for a room-in-space would render once with
  // an empty parents map and miss the channels redirect.
  const roomToParents = useAtomValue(roomToParentsAtom);

  const { roomIdOrAlias, eventId } = useParams();
  const viaServers = useSearchParamsViaServers();
  const roomId = useSelectedRoom();
  const room = mx.getRoom(roomId);

  // After P3c the Home tab is gone — /home/{roomId}/ stays as a deep-link
  // compatibility shim for cold-start push (sw.ts cannot read mDirectAtom or
  // roomToParentsAtom). Room-in-space rooms route into /channels/, everything
  // else falls through to the universal /direct/ list.
  if (room && !isSpace(room)) {
    const alias = getCanonicalAliasOrRoomId(mx, room.roomId);
    const orphanParents = getOrphanParents(roomToParents, room.roomId);
    if (orphanParents.length > 0) {
      const parentSpace = guessPerfectParent(mx, room.roomId, orphanParents) ?? orphanParents[0];
      const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace);
      return <Navigate to={getChannelsRoomPath(pSpaceIdOrAlias, alias, eventId)} replace />;
    }
    return <Navigate to={getDirectRoomPath(alias, eventId)} replace />;
  }

  if (!roomIdOrAlias) return <Navigate to="/direct" replace />;
  return (
    <JoinBeforeNavigate roomIdOrAlias={roomIdOrAlias} eventId={eventId} viaServers={viaServers} />
  );
}
