https://english.stackexchange.com/questions/1798/what-is-the-purpose-of-using-the-word-why-in-why-thank-you
Why is used here as an interjection. According to Merriam-Webster: —used to express mild surprise, hesitation, approval, disapproval, or impatience