Translate actor relative location and rotation to a different actor local space


I’m not strong in math and vectors, and I’m stuck with this issue.
The setup: 4 actors (let’s say A and B, X and Y) placed randomly by pairs (A and B near each other, X and Y near each other).
The goal: get actor B location and rotation relatively to actor A and place actor Y in the same location and rotation, but relatively to actor X.

I’m able to do this only when actors A and X are not rotated by axis-x or axis-y in world space.
How to properly translate the location and rotation to handle any rotation?

Thank you!