I don’t pretend to speak for Hamas, but one really likely thing that they did is prevent Saudi Arabia from throwing them under the bus by normalizing relations with Israel with no pre conditions on Palestine. Looking at Qatar and Saudi Arabia’s statements they have rallied at least a bit of support in the gulf.
As far as why they would try something like this, I think you can look at the 17 year blockade that Gaza has been living under and the increasing violence and evictions in the West Bank. Speaking of the West Bank, it is not under Hamas’ leadership, has had pliant, cooperative, secular leadership and that has been rewarded with brutality, intransigence, and an increased pace of illegal settlements. So desperation is another reason.
Obviously the brutality of the action is shocking, but it is an inevitability that we will see thousands of innocent civilians in Palestine pay the price for this. Hamas did not care about their lives either. But it is worth taking a moment to consider the misery that this brutality came from. Because I unless we learn something we will be watching this all happen again.