As mentioned before, this is one of Shakespeare's darker comedies, particularly with the inclusion of Feste's songs and the pranking of Malvolio. Other comedies with not-entirely-happy-endings would be Measure for Measure and The Marchant of Venice, whereas Much Ado About Nothing and A Midsummer Night's Dream end with almost all characters happy.
According to Stephen Greenblatt, the editor of The Norton Shakespeare, much of the plot of Twelfth Night comes from Barnabe Riche's story "Apollonius and Silla," from his Rich His Farewell to Militaire Profession, which was itself based on Italian and French sources. Riche's heroine, however, is not as fleshed out and thoughtfully rendered...