Is it a good idea to lose fat and gain muscle mass at the same time? Or Should I first lose fat and then gain muscles?
Neither, your first idea is like chasing 2 rabbits:losing both (in 99%+ of natural cases)
and the latter idea is the one to go if
you reverse the order.
When you gain muscle, you will gain some fat too.
so, it would be better to gain muscle before aiming to lose fat (bulking and cutting)