If you are flying back to the U.S. or Canada, then Sao Miguel, Azores would cap off an amazing Portugal trip and have the easiest connection vs Madeira. The best reason to visit Sao Miguel is this different perspective of "Portugal" will surely make you do a double take of this amazing country. These islands are off the American radar for some reason that I can't figure out. They truly are the gem of this country. Europeans have known about these "secret" islands forever. Granted, the weather could be hit or miss there or Madeira. Rain never stops us when we are there as there is so much to explore.
I would not bother with Spain for only a few days. A 2 hour flight from Lisbon is easy and inexpensive using the different airline options.
If you want to look over my PDF guide I wrote of the Azores islands I have visited, just give me your email address here or in a private message or directly at brengina2@hotmail.com. It may help you make an informed decision.