mesh rotation error after i attached the bones
Once you've parented your mesh, you often need to corect the IK Pole Angle so that the mesh doesn't get twisted by the IK:

Also, always bend a bit the knees and elbows in Edit mode so that Blender knows how to bend these limbs once rigged: