In chapter 678, why did Madara suddenly turn into Kaguya? Was this all planned from beginning?
When Black Zetsu impaled Madara, he transfered Kaguya's will into Madara. By this process, Kaguya was revived by using Madara's body as the host vessel. And yes, it was planned from beginning by Zetsu.
Black Zetsu's history:
He was created by Kaguya and served only her. He acted as if he was Madara's creation, so he could facilitate the revival of his "mother", aka Kaguya. To do this, he planned the activation of Infinite Tsukuyomi by influencing Madara and the Akatsuki.
Further reading: Kaguya Ōtsutsuki
Yes, it was planned. As you see, Black Zetsu is Kaguya's servant, and he manipulated the Uchiha tablet to deceive Madara to revive the Ten Tails. This was one in order to become the Sage of Six Paths in order to become the vessel for Kaguya's revival.
We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.
Black Zetsu is a shapeless manifestation of Kaguya's will, created before she was sealed by Hagoromo and Hamura. It planned to manipulate Indra Otsutsuki and his descendants to one day wield the Rinnegan and activate the Infinite Tsukuyomi.
Once Madara activated the Infinite Tsukuyomi and trapped everyones chakra inside the God Tree, Black Zetsu then stabbed Madara while he was sapped of his chakra, and uses his Ten Tail Jinchuriki body and combined his will to create a pseudo Kaguya.