Imaam Ibn al-Qayyim (may Allaah have mercy on him) said in his famous book Al-Waabil As-Sayyib Min Kalaam At-Tayyib:
…So if Allaah intends goodness for His slave [after he has fallen into a sin], He opens up the doors of repentance for him and puts [in his heart] the feeling of need [for Allaah] and makes him dependant upon Allaah. Allaah grants him humbleness and brings him closer to Himself through enabling him to preform good deeds, and this one sin was the reason behind a [mountain] of good deeds, so much so that the enemy of Allaah [Iblees] will say, "O how I wish I had never made him commit that one sin!"
This is the meaning of some of the Salaf's saying:
"Verily, a slave commits a sin and thereby enters Jannah [because of it] and he preforms a good deed and enters Hell because of it."
They said, "And how is this?"
And it was said:
"[This is because] he commits the sin and he does not cease shedding tears concerning it, fearing [its consequence] regretting it, feeling shameful before his Lord the Most High. Hanging his head low with a broken heart, because of this, the sin is in truth more beneficial for him as it is the source of many good deeds after it. And through it the slave attains salvation and success, so much so that this sin becomes the reason for the slave to enter jannah [i.e through the mercy of Allaah].
And he [might] preform a good deed and does not cease in mentioning that, and feeling full of pride and is amazed at himself saying "I did and I did!" [i.e boasting] so pride enters [his heart] which results in his destruction."