Arizona Republican Sen. John McCain, whose fierce independent streak earned him a reputation as a principled and at times frustratingly maverick politician, has died after a months-long battle with brain cancer at the age of 81.

McCain led a storied life that included a career as a naval aviator; a five-and-half year stint in an infamous North Vietnamese torture camp known as the Hanoi Hilton; two presidential runs, including one as the party standard-bearer in which he lost to America’s first African American president; and an influential term as chairman of the Senate Armed Services Committee, a position he used to tirelessly champion increased resources for the U.S. military, while chiding presidents of both parties for, in his view, failing to confront dictators and despots who threatened American democratic ideals.

McCain was diagnosed with a virulent form of cancer in July of 2017, a brain tumor called a glioblastoma, for which he elected to stop treatment Thursday. It was a diagnosis he greeted with equanimity and characteristic optimism.

"Maybe I’ll be gone before you read this,” he wrote in his final book, The Restless Wave: Good Times, Just Causes, Great Fights, and Other Appreciations, released May 22. “I hope those who mourn my passing, and those who don’t, will celebrate as I celebrate a happy life lived in imperfect service to a country made of ideals, whose continued success is the hope of the world. And I wish all of your great adventures, good company, and lives as lucky as mine.”

[Trump: 'Deepest sympathies and respect' for McCain family]

McCain will be remembered for many things, but mostly for his efforts to serve as a moral compass in a time of rampant political expediency.

President Trump notably disparaged McCain during his 2015-2016 campaign, dismissing McCain’s status as a war hero because he was taken prisoner. “I like people who weren't captured,” Trump said in 2015.

McCain would go on to oppose Trump on issues ranging from torture, to service by transgender troops, to Trump’s pardon of Arizona Sheriff Joe Arpaio, which McCain said undermined Trump’s “claim for the respect of rule of law.”

In August 2016, it was McCain who rose on the Senate floor, and in a dramatic display of political theater, extended his arm and turned his thumb down to cast the deciding vote that killed the Republican effort to repeal Obamacare.

McCain, ever the moralist, complained that the process, which did not follow Senate procedures known as “regular order,” was flawed.

“He is loyal to his friends. He loves his country. And if he has to stand up to his party for his country, so be it. He would die for this country,” said his longtime friend and fellow Sen. Lindsey Graham, R-S.C., in an appearance with McCain in March of 2017.

“I love him to death,” Graham said, as McCain appeared to wipe away tears.

“In truth he has been an equal opportunity antagonist,” wrote McCain biographer Robert Timberg, describing McCain’s first run for president in 2000. “It doesn’t help that he has taken positions, championed legislation, and advocated policies that have turned one bloc of supporters or another against him.”

Timberg wrote The Nightingale’s Song, a chronicle of how McCain’s life intertwined with four other Annapolis grads against the backdrop of Vietnam.

Ever the hawk, McCain was remarkably prescient in 1994 when he called for taking a hard line against North Korea in the months before the Clinton administration reached an agreement that was intended to end the North’s nuclear program.

McCain had advocated military strikes to take out North Korea’s lone nuclear reactor, perhaps aware the Pentagon was secretly considering the option, and accused North Korea of simply stalling until it could produce an arsenal of nuclear bombs.

“By allowing ourselves to be drawn into extended and ultimately fruitless negotiations with North Korea, we let the clock run out, and allowed the crisis to become so acute that it lacks a remedy short of military action,” said McCain in an October 1994 speech on the Senate floor after the agreement was reached.

McCain was also a strong backer of the invasion of Iraq in 2003, despite the failure to find weapons of mass destruction, as well as an advocate of the “surge” of U.S. forces in 2007, which he believed saved the Iraq War from defeat.

John Sidney McCain III was born Aug. 29, 1936, into a family with a long Navy tradition. Both his father and grandfather were four-star admirals, and McCain received a commission to the U.S. Naval Academy in 1954, where he quickly earned a reputation for having a rebellious streak.

A naval aviator during the Vietnam War, he narrowly escaped death on the deck of the USS Forrestal when the aircraft carrier caught fire during combat operations in the Gulf of Tonkin in 1967, taking the lives of 134 men. Later that year, his A-4E Skyhawk was shot down by surface-to-air missiles over Hanoi, and McCain was held prisoner until 1973.

When the North Vietnamese discovered McCain’s father had been named commander of U.S. forces in the Pacific, they offered to release him early as a propaganda ploy, an offer McCain refused. He endured more than five years of torture that left him with permanent physical limitations, including the inability to raise his arms above his head. He also attempted to take his own life after he broke under torture and was forced to write a false confession.

McCain retired from the Navy with the rank of captain, and entered politics in his home state of Arizona, elected first in 1982 as a congressman, and then as a senator in 1986.

McCain was one of five senators, known as the Keating Five, who were accused of corruption in 1986 in the probe of improper intervention on behalf of Charles Keating, a savings and loan executive, in return for campaign contributions.

McCain was cleared of wrongdoing, and went on to champion campaign finance reform, eventually winning passage of the McCain-Feingold Act in 2002.

In 1999, in preparation for his bid for the White House the following year, McCain and his longtime chief of staff Mark Salter co-authored a compelling memoir of his life, Faith of My Fathers, which became a national bestseller. McCain lost the 2000 primary to George W. Bush, but won the nomination in 2008 to face Democrat Barack Obama, a one-term senator from Illinois.

With polls showing he would lose the general election by several percentage points, McCain made the decision to pick a relatively unknown and untested politician as his running mate, Alaska Gov. Sarah Palin, in an effort to change the dynamic and excite the Republican base.

In doing so, he passed over his first choice, close friend Sen. Joe Lieberman, who would have become the first vice presidential candidate to run on both a Democratic and Republican ticket.

The story was dramatized in the 2012 HBO movie “Game Change,” the accuracy of which was endorsed by former McCain adviser Steve Schmidt in an interview with MSNBC at the time of the movie’s release.

Lieberman, now retired, and Graham were McCain’s closest friends in Congress.

“The Three Amigos” were inseparable, and McCain dragged them all over the world as part of congressional delegations to war zones and world hotspots.

While McCain could unleash a blistering attack full of moral outrage from his perch on the Armed Services Committee or from the Senate floor, he was known also for his self-effacing humor.

McCain liked to point out he graduated fifth in his class in Annapolis, fifth from the bottom, he would add after a beat. His low class rank was due in part to all the demerits he racked up as a consequence of his notorious rebellious streak.

In his later years, McCain would ruefully refer to his younger self as “callow, conceited and often stupid.”

“In short, I acted like a jerk,” he once wrote of his time as a midshipman.

When Phoenix’s City Council voted in 2016 to name a terminal at Phoenix Sky Harbor International Airport after him, McCain said in a statement, “I have rarely felt at once so honored and yet so unworthy of an honor as I do today.”

In his last year, McCain took on the mantle of elder statesman and loyal opposition to his own party’s president.

“Congress must govern with a president who has no experience of public office, is often poorly informed and can be impulsive in his speech and conduct,” McCain wrote of Trump in a Washington Post op-ed. “We must respect his authority and constitutional responsibilities. We must, where we can, cooperate with him. But we are not his subordinates. We don’t answer to him. We answer to the American people.”

Through it all, McCain said he has never lost faith in his country.

“I still believe in America. I still believe we're the greatest nation on Earth. I still believe that we have the best military and by far we're still a shining city on a hill as Ronald Reagan called us,” he said on CNN in March.

In a speech in Italy in September he said, “Put simply: No one has ever gotten rich betting against America, my friends, and now is not a good time to start.”

Asked later that month how he would like to be remembered, McCain suggested an epitaph to CNN’s Jake Tapper: “He served his country and not always right. Made a lot of mistakes. Made a lot of errors, but served his country. And I hope we could add, honorably.”

McCain is survived by his wife of 37 years Cindy, along with children Meghan, Jimmy, Jack, and Bridget, as well as his first wife Carol, and their children Andrew, Douglas, and Sidney.