It doesn’t always happen. You think of a great idea for a story and start off with a bang, only to hit the wall somewhere along the way. That great idea never finds a plot to build on. It doesn’t know where it’s going or what will happen at the end. It doesn’t know how the characters got where they are now, or where they’re going, or how they’re going to get there. Sometimes you realize that it wasn’t really that great an idea and you cross it off the list. Other times, though, it gets its hooks in you and you keep coming back to it, hoping for a breakthrough.
Sometimes, but not always, the breakthrough comes in a rush and the whole story comes seemingly out of nowhere, laid out for you from beginning to end. All you have to do is fill in the details. I don’t know what number that is of the rewards of being a writer, but it must be pretty close to the top.