How to fill 5 inch deep gap above and below window on internal wall
Gaps around windows are common (there's a reason why they're called "rough-in"). As long as the gaps aren't larger than the trim, you're fine. Oddly enough, the old trim looks like it was attached to the window. That would explain the gap (it wasn't visible from the inside).

The unusual thing here is the size. Expanding foam is your friend here, but be sure it will fill a gap that large. Not all foam will expand 1" or more but there are types that can.