This doesn't make any sense to me.
Lopetegui was contacted by Madrid, he was negotiating with them agreed to join them after the world cup, some players got wind of it somehow it leaked and he had to make a hurried announcement.
This isn't the first time a coach is signing for another job while still at the current job. Most career people interview and agree terms for new employer while at old employer
LvG signed to join Man Utd while still at Holland at World cup 2014, Conte signed to coach Chelsea while still coach or Italy at Euro 2016, Guardiola agreed to join City while still Bayern coach, Mourinho agreed to join Chelsea while still in Madrid, Mou agreed to join Madrid while still at Inter.
So I honestly don't get the rationale and throwing away the chance at a world cup because of this, an entire nation, the players were looking forward to it.
If Spain doesn't win, then the whole nation will say, well, who knows what could have happened if we didn't sack the coach.