In a Halloween hoax gone horribly wrong, an off-duty, undercover cop shot a teen prankster in the groin early yesterday after the kid and his hooligan pals attacked him in upper Manhattan on his way home from work.

The five rowdy male revelers — all between 16 and 20 years old — were celebrating the pre-holiday “mischief night” in Washington Heights yesterday at 12:30 a.m. by jumping from a large cardboard box in order to spook passers-by.

Then the group picked the wrong guy to mess with.

When one of them jumped in front of the 34-year-old Bronx narcotics cop — who was walking to his building after getting off duty — he became furious and confronted the pack.

The argument turned heated and he dialed 911.

While the cop waited for backup, one teen thug, Joseph Peralta, 18, pinned him against a parked car while a buddy tried to pummel him with a metal trash can, police said.

The officer identified himself as a cop, then drew his weapon and fired one shot that hit Peralta in the groin, police said.

Peralta was taken to Columbia Presbyterian Hospital, where he was in stable condition and placed under arrest, police said.

The officer suffered a scratch to his head and was also treated there.

The other four pranksters were being grilled last night at the 33rd Precinct station house but had not yet been charged.

Peralta was not allowed to receive visitors at the hospital yesterday afternoon.

The young rabble-rousers’ families said they were all worried about their children, whom they had not seen since the previous night.

“The cop got scared, and he attacked one of the boys,” said Joseph’s father, Paulino Peralta, 50. “My son came to defend his friend. He didn’t identify himself as a police officer. What would have happened if he had killed my son?”

Last night, when cops escorted Peralta — wounded, limping and handcuffed — into the police station through the back door, a mini-riot erupted as family members and friends started screaming at the cops.

Agueda Honoret, 25, who lives in the neighborhood and witnessed the shooting, said the kids started banging on her window telling her to call the cops after Peralta was shot.

“Joseph was on the ground, he had his hands over his face, and he was saying, ‘Please, please, don’t shoot me,’ ” Honoret recalled. “All his friends were standing there, but they couldn’t do anything because he kept pointing the gun at them, too.”