The Russian invasion of Afghanistan failed for many of the same reasons that the US war in Vietnam failed. In both cases, the superpower underestimated the difficulty of fighting against a guerrilla insurgency in difficult terrain when that insurgency was highly motivated to fight.
In Afghanistan, the resistance to the invasion was fierce and highly motivated. The resistance was motivated at least in part by religion, which tends to give people a very strong incentive to fight hard and not give up. The Russians did not understand that the Afghans would be so strongly motivated and so they did not understand how hard the war would be.
The Russians also did not understand how unmotivated its own troops would be. This was partly because many of the Russian troops were Muslims from the Central Asian part of what was then the Soviet Union. These troops were not strongly motivated to fight against fellow Muslims.
So the invasion failed because it is hard to fight in Afghanistan, because the Afghan resistance was so motivated, and because the Russian troops were not motivated.