I tried to ask chatgpt, initially asked me to do a "clean boot". I'm using MacBook Pro M1.
Option 1 (Clean boot): Shutdown, wait a few seconds at least 30 seconds. Hold the power-on button until you see "Loading startup options", then click "restart". - This didn't work for my laptop.
Option 2:
In terminal, run
sudo rm /Library/Preferences/com.apple.windowserver.displays.plist
Then restart and reconnect the display. "This forces macOS to rebuild display preferences".
I did option 2 but instead of restart I did shutdown and did the option 1 again. It worked, I can now extend or mirror to my external monitor. Not sure if option 2 alone can fix it. Hope this helps. Please share your experience.