#Python 3.8, 104 74 65 60 57 bytes
Python 3.8, 104 74 65 60 57 bytes
lambda n:(-2,6)[n>4*(x:=(n**.5+1)//2)*x+2*x]*x+2+~n+8*x*x
Edit: Thanks to Johnathan Allan for getting it from 74 to 57 bytes!
This solution uses 0-based indexing.