What led to this spell?
It is unclear how spells are invented or what leads to them.
Did someone create it, or did people just randomly do wand movements
and say things?
Spells are created by Wizards. In the Half Blood Prince, Harry discovers numerous spells and hexes that were invented by Snape as he states later in the story,
You dare use my own spells against me? It was I who invented them--I,
the Half-Blood Prince!
And he does puts effort into inventing them which are evident by the writings in his potions book.
Although it is said that Wizards use magic without inventing or even knowing it, I could not find any incident where a wizard invents/comes across a spell by accident.
If so, wouldn't this be very dangerous?
Yes it is dangerous as Luna Lovegood's mother dies trying to invent a new spell.