import React, { ReactNode } from 'react';
import { useParams } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { decodeRouteParam } from '../../pathUtils';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { IsDirectRoomProvider, RoomProvider } from '../../../hooks/useRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { JoinBeforeNavigate } from '../../../features/join-before-navigate';
import { useDirectRooms } from './useDirectRooms';
import { mDirectAtom } from '../../../state/mDirectList';
import { Membership } from '../../../../types/matrix/room';

export function DirectRouteRoomProvider({ children }: { children: ReactNode }) {
  const mx = useMatrixClient();
  const rooms = useDirectRooms();
  const mDirects = useAtomValue(mDirectAtom);

  const { roomIdOrAlias: rawRoomIdOrAlias, eventId: rawEventId } = useParams();
  const roomIdOrAlias = decodeRouteParam(rawRoomIdOrAlias);
  const eventId = decodeRouteParam(rawEventId);
  const roomId = useSelectedRoom();
  const room = mx.getRoom(roomId);

  // useDirectRooms can lag m.direct / allRooms during catch-up; allow joined m.direct rooms.
  const isJoinedDirect =
    Boolean(room) &&
    room!.getMyMembership() === Membership.Join &&
    (rooms.includes(room!.roomId) || mDirects.has(room!.roomId));

  if (!room || !isJoinedDirect) {
    return (
      <JoinBeforeNavigate
        roomIdOrAlias={roomIdOrAlias ?? rawRoomIdOrAlias!}
        eventId={eventId}
      />
    );
  }

  return (
    <RoomProvider key={room.roomId} value={room}>
      <IsDirectRoomProvider value>{children}</IsDirectRoomProvider>
    </RoomProvider>
  );
}
