The phrase appears in "The Clockmaker" (1817) by Thomas Haliburton but surprisingly not directly by Lewis Caroll in either 'Alice in Wonderland' (1865) or 'Through the Looking Glass (1871).
Where does the idiom come from?
It is believed to be an allusion to the grim effect of mercury poisoning on workers (hatters) manufacturing felt hats.
Mercury poisoning affects the nervous system, with dementia a common symptom. Daily direct contact with the metal made hat-makers particularly vulnerable to the affliction.
What is the Alice in Wonderland connection?
There is "A Mad Tea-Party" in Alice where Hatta the Hatter and the March Hare are initially referred to as "both mad" by the Cheshire Cat. It is the zany antics of Hatta & the Cheshire Cat that are being referenced in modern usage.
English Language Teaching Pack - only £1.99