There is a simple automation here which turns lights on and off from a motion sensor. You may be able to adapt it to fit your situation.
Motion activated lights automation
The key point is that it uses trigger.to_state.state in the action, so that the action reflects the state of the trigger.