Peace be upon you,
May Allah reward you.
It is indeed striking how thoughts can crowd our minds intensely during prayers, revealing the combined forces of evil from the devil and the commanding self, diverting the worshiper from facing the Almighty...
Imam Khomeini (may his soul rest in peace) said: "Know that the first condition for a fighter in this position and other positions, which can be the foundation for overcoming the devil and his soldiers, is to control the bird of imagination, for this imagination is a soaring bird that lands on every branch, bringing much misery, and it is one of the means by which the devil makes a person helpless."
The way to manage this issue lies in training and repeatedly bringing this bird back. Although this bird flies, there is a string tied to its leg, so whenever it tries to fly away, one must pull it back to its place to prevent it from bringing misery and depriving one of humility in prayer, supplication, and focus while reading beneficial books.
Imam Khomeini (may his soul rest in peace) also said: "It is possible, through experience, to control part of your imagination and pay close attention to it. Whenever it wants to turn to a trivial matter, redirect it towards other matters, such as permissible things or more significant issues."
If a person succeeds in reaching this level, where they can think whenever they want and stop thinking whenever they wish, and only think about what they desire, they have reached the highest degrees of perfection.
Factors that help with this include focusing during acts of worship, remembering the fear of Allah when standing before Him, and trying to find means that assist in concentration, such as changing the Quranic chapter during prayer, performing recommended supplications, and engaging in optional acts that bring one closer to Allah, enhancing the joy of closeness and dialogue with Him, and increasing humility and submission to Allah.
For more information, you can refer to [Question 924](
https://www.islamq2a.com/924/).
Regarding useful books on this subject, we recommend:
[Secrets of Prayer by Sheikh Habib Al-Kadhimi](
https://alseraj.net/wp-content/uploads/2021/03/%D8%A3%D8%B3%D8%B1%D8%A7%D8%B1-%D8%A7%D9%84%D8%B5%D9%84%D8%A7%D8%A9.pdf)
You can also review ethical books in [Question 420](
https://www.islamq2a.com/420/).
May you be successful in all good.