Is it permissible to think/imagine about some halal sexual thing (for example to think about having sex with wife)? And what if one ejaculates due to such thinking?

Thinking about sex with wife is no matter but extra things whatever you mentioned is only for medical things allowed because of emergency