One of the thing you may have done wrong IMO is leaving your cav behind...

When faced with archers and if the infantry line is sufficently lagging behind, I often use my cav to charge on those missile units simply getting the m to skirmish back behind the line of infantry lets you concentrate your fire on higher value troops...

Logically, doing so, archers should have shot less volleys of arrows and your musketeers should have made more kills in his infantry...

You're talking about a valley... Was there a river and a bridge ? Or was it more of a mountainous area ?

If so, could you use a hill to place your battle line thus making the enemy climb up to you....

You should have loosened you pike formation and closed it in time with the enemy advance...

As to their cavalty trying to flank you, try maybe to lure them away with your cav w/o engaging or try to drive them towards your pikes...

The total balance should then have been in your favor...

For the finishing touch, if possible, when the two infantry line engaged, you should have tried to send your cav in the back of the enemy line (on any point where you thought your own line was breaking) to rout those units and then repeat with any still fighting...

I don't know the stats for muskets but IMO they should have been longer than the Eng Bows (correct me if i'm wrong...)

Anyway, it proves that despite a faulty AI, one never knows...Surprise...