The radio freqencies used for WiFi and Bluetooth overlap a lot. Originally WiFi was just on 2.4 GHz, but now has two other bands, one at 5GHz and another at 6GHz. BT operates in the same 2.4GHz radio range as the WiFi in that band. So WiFI and BT can interfere. There are other uses for those frequencies, including wireless telephones for landlines, remote controls, etc. The wavelength at the 2.4GHz is 0.125 Meters, about 5 inches. So, there will be a peak in the signal every 2.5 inches or so from every device in the band. And when those peaks and valleys meet, they add together or cancel out, depending on the distance between the devices transmitting them and their own spatial relationships. Imagine your desk as a sea of peaks and valleys of signals from every device using the 2.4GHz band all merging, creating a continuously changing environment. And moving any of the various devices as little as an inch can make a huge difference in the signals it is seeing.
Now, most of what is there is noise, but there is also a signal that is key to the connection. When the Signal to Noise ratio gets too low, the signal disappears into the Noise and the device disconnects. You mentioned an upstairs neighbor. If that neighbor moves one of their devices, even just a little, it changes what is going on in your area as well. And if you have downstairs neighbors, they, too, even though not connected, can be sending out radio signals that also show as noise to your systems.
This constantly changing noise background is why the systems have huge redundancies built in to the logic of the receivers and transmitters. You "pair" BT devices because that way each can now ignore all the random signals from the other devices they can hear and listen only for the paired device(s) signals. But if the noise floor is too strong, it can overwhelm the receiver and it cannot hear the paired device in the noise. There are limits to the "magic."
It can, of course, also be something in the actual BT circuits in the iMac. That model is now 6 years old, and the BT transmiter/receiver may be declining. It does happen. The fact that when you lose connection you lost it to both of the devices at the same time would point to the iMac as the failure point. You could get a wired trackpad and a wired mouse to go along with the wired keyboard and solve the problem that way for probably the least amount of money. That's what I would do, but I would also be saving my money to get a newer Mac pretty soon. The iMac is trying to tell you it's old. Listen to it.