I think it's very outdated. I know it from books but I've never heard it used in real life. (I'm a U.S. native speaker).
It means "I don't believe it." The implied context is an imaginary bet. "I'm so sure it is untrue, that I'm willing to bet on it. If I lose, I have to eat my hat."
Some other phrases that mean "impossible:"
"... then I'll be a monkey's uncle." (Outdated).
"...then I'm the Queen of Sheba." (Possibly regional or ethic? The "impossibility" aspect is that "the Queen of Sheba" = the ultimate in beauty.)
"...when pigs fly."
"...when hell freezes over."
None of these are "bad language" but they are basically impolite because they express an EXTREME degree of disbelief.
Steve Jobs had said that Apple would never create any Windows software. In 2003, he introduced his announcement of iTunes for Windows with a big slide that said "Hell froze over."