Spanish banks will have to pay back their customers after charging them excessive mortgage payments, Europe's top court has ruled.

The European Court of Justice said Wednesday the banks, which include Banco Popular and Banco Sabadell, were charging unfairly high interest rates on their floating-rate mortgages, and ordered them to reimburse customers who paid too much.

Analysts say the bill could reach over €4 billion ($4.2 billion).

The ruling came as a surprise to the banks and most analysts, who were expecting the banks to win the case. Stocks in the banks dropped as much as 10% after the ruling.

"Floor clauses" impose minimum interest rates that mortgage holders have to pay even if interest rates fall below that threshold. They were made illegal in Spain in 2013, when the country's supreme court ruled them "unfair."

Related: Spain has no government and 3% growth

The case on Wednesday was centered around the claim that the banks should repay the sums they collected thanks to these floor clauses even before they were made illegal.

Spain experienced a huge housing bubble in the early 2000s, when home ownership rates topped 80%, the highest across developed economies. But house prices collapsed in 2009, amid the global financial crisis, and mortgage debt became a huge problem.

Unemployment skyrocketed to 26% and tens of thousands of people have been evicted, according to Human Rights Watch report.