Is the sentence grammatically correct? Could you explain more about it's grammar?
I was to be staying ...
Yes, within the right context.
It describes a situation where you are recalling a past plan. In the past, you were planning to stay on your friend's sofa. When talking about what the plan was you can say "I was to be staying on a friend's sofa". But I would add two caveats:
It's an older and/or slightly more formal construction. It's valid, but in modern settings you would more likely construct it as "I was planning to stay on a friend's sofa" or "At the time I planned to stay on a friend's sofa." Omitting the specific verb (planning) and substituting in "to be" isn't really that common these days.
Staying may or may not be the correct word. While technically correct it may parse better to english speakers if you were to say sleeping.