I did not understand a thing from the last minutes of "A Scandal in Belgravia". Are we actually taking a look at Irene about to get killed, and is she hallucinating when she sees Sherlock? Or is Sherlock having a flashback? And if so, why did he receive the message only then in the present time.
It's actually quite a simple, albeit far-fetched ending.
Firstly, Dr. Watson comes into the apartment with the phone. Sherlock asks for it and this conversation occurs:
This obviously implies that she texted Sherlock goodbye and he never heard from her again. At this point, we as the audience are meant to believe this was their final communication and Sherlock is still upset/annoyed given her actions prior to this (with the entire Bond Air scandal).
Watson then leaves and Sherlock, once he's aware John is gone and can't see him scrolls through all the texts:
Again, this implies that he got one last message from her and he's merely reflecting on it.
He looks out the window into the rain and we get Irene Adler's flashback. This is all done to show the story as Mycroft described it - her being killed by the terrorists. This all fits in with what we, the viewers, have been told, and so we accept it. It's moving, quite sad, and we see Irene send her final text before the screen goes to black...
... Only for us to hear the little groan that Sherlock's phone makes when he gets a text from her. Irene's eyes open and she realises that he is her supposed executioner, come to rescue her. He tells her to run and we see her smile.
Cut back to present day and Sherlock smiles away to himself thinking of The Woman.
The idea is that he rescued her. But he's Sherlock Holmes, the greatest detective in the world. No one knew he did it, not John or Mycroft or anyone else. And he didn't want them to know, so he didn't display any emotion regarding her in their presence (until he was alone at the end and smiled).
He didn't see the message at the end of the episode for the first time, he simply opened it to remind himself of the moment.
Irene is most definitely not hallucinating, but rather is being saved by Sherlock (although disappointingly, it seems unlikely she ever got her dinner date).
Co-creator and writer Steven Moffat clarified this: