I would suggest to use states.
A LONG time ago, when I first started to program, I tried to make a simple AI for a cat to chase a mouse, and then if the mouse got far enough a way, to stop following and return home. If the mouse was close enough, the cat would attack.
Since I was new to programming, I used one massive, hard to troubleshoot if-else-if-else algorithm, with lots of nested variable checks, etc. It was horrendous.
A state system would be something like ‘idle’, ‘fighting’, ‘chasing’, ‘goingHome’, ‘dead’.
Then you break up what to do in these specific states.
For example, if he is idle, he could be checking for distance every .25 seconds. If the user is within a set range, he switches to the ‘chasing’ state.
While in the chasing state, you check if the user is out of range, if he is, switch to ‘goingHome’ state. If the player is in attack range, switch to ‘fighting’ state.
This breaks things down into small, manageable sections of code. At any given state, there are limited number of options, easier to handle.
Usually people include an ‘enter’ and ‘exit’ function associated with states, as well as a ‘loop’. For example, when you enter the ‘idle’, state, you call the IdleEnter function. This would initialize any variables or values or animations, etc. Then when you switch from Idle to another state, you would first call the ‘IdleExit’ function to breakdown anything needed, before calling the new states ‘Enter’ function.
Once the Enter function has been called, you would then loop the states ‘Loop’ function. So to switch from ‘Idle’ to ‘Fighting’, it would go like this:
// switching from idle to fighting
IdleExit();
FightingEnter();
FightingLoop();
Good luck, I hope this enough to get you started at least.