I can not understand the phenomenon but I can describe it to you. I'll take light as a particle (photon particle). Considering the following is your main concern:
I was wondering exactly why a ray of light changes direction when moving from one optical medium to another.
The discussion will be followed by the Feynmann lectures on QED:
Grand Principle: The probability of an event is equal to the square
of the length of an arrow called the “probability amplitude.”
-General Rule: for drawing arrows if an event can happen in
alternative ways: Draw an arrow for each way, and then combine the arrows (“add” them) by hooking the head of one to the tail of the next. A “final arrow” is then drawn from the tail of the first arrow to the head of the last one. The final arrow is the one whose square gives the probability of the entire event.
Refraction: Consider an experimental setup where you have a light source in an air medium and a photon detector in the water medium. We want to calculate the
the probability that a photon will get from the light source to the detector.
For each path, you have a vector (arrow) that rotating around and around and we need to stop the arrow as times up ( time is taken by light to get the detector). We do the same for each path.

Source: QED The strange theory of light
The graph will be a curve starts up high, goes down, and then back up again; the most
important contributions come from the places where the arrows point
in nearly the same direction (where the time is nearly the same from
one path to the next), which is at the bottom of the curve. That is also
where the time is the least, so all we have to do is find out where the
time is least.
Which is the so-called Fermat principle The rest of it follows from the Fermat principle. See here.