There is a very good - and very disturbing - piece by reporter Sarah Chayes entitled The Ides of August that is well worth reading to understand why we failed so abysmally in Afghanistan. See also an interview with her here which is equally as good (and equally as unsettling).
The focus these days is on the incompetence of our withdrawal from Afghanistan, but perhaps the more important issue is the much larger incompetence we as a nation exhibited during the 20 years we occupied Afghanistan.