One way to keep bones from twisting in odd directions is to keep the bones in a particular chain all axis aligned…
all with the Z- axis up… or all with the Xaxis down… etc…
an easy way to keep track of which direction those Pesky bone Axis are pointing is to turn on the ‘bone axis’ display…
Select your bone > Properties Panel > Armature (the little man Icon) > Display > check the box that says “Axes”…
now your bones all display axis arrows that let you know exactly the alignment of each bone’s Axis…
the important thing… is keeping each bone aligned with it’s parent as close as possible…