Image copyright Matt Cardy

Prime Minister Theresa May has been forced to quit. Parliament is deadlocked. Both the Conservative and Labour parties are deeply divided and deeply unpopular.

What's more, with days to go before there is a new occupant of No 10, no-one has identified a clear route to an agreement that will avoid an outcome pretty much everyone says they want to avoid - a costly and disruptive no-deal Brexit. So, how did the UK end up here?

For the past few months, the BBC's Panorama team has spoken to those with first-hand knowledge of the negotiations - in Brussels, Paris and Dublin as well as Westminster. We've interviewed at length, on and off the record, the men and women who tried and failed to make a Brexit deal that both the UK and the EU could agree to.

This is an account of 10 crucial mistakes, mishaps and misunderstandings that might explain why we haven't left yet.

1. The UK had no plan for Brexit

Getty Images I would love to say that there was a clear manual on my desk... that said ‘Brexit - how to do it’ but there was no plan

George Bridges was a new minister in the Brexit department created from scratch in 2016 when Theresa May became prime minister - a job she only got because the UK voted to leave the EU.

At least Bridges had an office. Secretary of State David Davis's political advisers had to share a cupboard, while the department's top official had to change his office three times in one day. It was chaos.

Lord Bridges, who was a junior minister, assumed that the thinking about Brexit must be taking place somewhere else:

"I was very much under the view that there would be somewhere in No 10 a very small, very secret group, putting together an almighty chart, a big plan of how we were going to negotiate and crucially what our overall objectives were. So, the prime minister - rather like a Bond villain - would be sitting with her white cat on her lap with this big plan behind her. I'd love to say that that room existed. I never found it."

He wasn't the only one. In Brussels, top EU officials were waiting to see what the UK would propose.

"We thought they are so brilliant there will be, in some vault somewhere in Westminster, a Harry Potter type book with all the tricks and all the things in it to do."

Frans Timmermans, first vice president of the European Commission, was shocked by what he saw and heard. Or rather what he didn't:

"I thought, 'Oh my God, they haven't got a plan…they haven't got a plan… it's like Lance Corporal Jones'. It was, 'Don't panic, don't panic,' running around like idiots."

Image copyright Getty Images Image caption David Cameron, 2015

The truth is there was no plan for Brexit when the UK voted to leave. David Cameron had no Plan B when he called the EU referendum. One senior official says he stopped civil servants preparing one as he was fearful it might leak.

The main Leave campaign, led by Boris Johnson and Michael Gove, had decided not to produce a Plan A. They knew the choices that would have to be made would split their coalition of support.

Theresa May came to office without a plan. Indeed, she barely mentioned Brexit in her speech in Downing Street.

2. The EU did have a plan - a plan for its own survival

Getty Images If it’s all ‘win win’ to easily withdraw from the EU, then that would mean the end of the European project

Speaking to the BBC, former French President Francois Hollande says he told his fellow EU leaders straight after the referendum that the UK would have to pay a price:

"Brexit might lead to a slippery slope where others, and particularly those under the sway of populists, might decide to follow what the British have just been doing."

EU leaders sensed that populism was on the march. Brexit was followed by the election of Donald Trump.

When the new US president called the other President Donald - Donald Tusk, the president of the European Council - he asked a question with a hint of menace: "Who's next?"

With elections due in France and the Netherlands in 2017, this was no mere taunt. The leader of the French National Front, Marine Le Pen, was campaigning for "Frexit". Polls suggested victory was likely for the Dutch far right leader Geert Wilders. Hungary, Austria and Italy were already governed by politicians who were highly critical of the EU.

There were tears in the office of Jean-Claude Juncker, the president of the European Commission, when he and his officials heard that the UK had voted to leave.

Juncker's right hand man was a formidable German lawyer called Martin Selmayr, thought by many to be the most important man in Brussels. Giving his first British broadcast interview to Panorama, he says:

Getty Images Brexit was an existential crisis for the European Union

"I think the most important thing at this moment in time was to preserve the unity of the other 27 member states - to make sure that in the process that followed, all 27 saw eye to eye …[and] to use this moment not to further weaken the [European] Union, not the beginning of the end, but the start of a new beginning for the European project," says Selmayr.

When Selmayr met the British minister he knew best, David Lidington, who'd been Minister for Europe for many years and who would go on to become Theresa May's de facto deputy - he spelt out what this would mean. Lidington recalls this conversation:

"He said to me, 'Look David, there's not going to be the traditional EU late into the night, into the wee small hours, horse trading on this. It'll be the Commission that your side talks to. We are not going to give your prime minister the chance to try and pick us off."

The UK was no longer to be treated like a member of the club, in which it could seek to build alliances and divide and rule the 27 countries still inside. It would be treated as if it had already left.

Negotiations would take place not with representatives of every country but with a team led by one man - a suave silver-haired Frenchman called Michel Barnier. In his first British broadcast interview since the negotiations began, he told Panorama:

"Everybody will have to pay a price - EU and UK - because there is no added value to Brexit. Brexit is a negative negotiation. It is a lose-lose game for everybody."

3. "Brexit means Brexit" but what on earth did that mean?

Getty Images It was a surprise to see that the prime minister had chosen to define Brexit in the hardest possible terms

Philip Hammond didn't like what he was hearing. Theresa May was delivering her first speech as prime minister to the Conservative Party Conference in 2016, and her new chancellor of the Exchequer was sitting in the audience.

"I was trying to keep my face dead straight, conscious that there were cameras on me," he says.

May began by saying that "Brexit means Brexit and we're going to make a success of it". That came as no surprise to Hammond. He'd heard her use the phrase many times before.

But then the prime minister continued: "Our laws will be made not in Brussels but in Westminster. The authority of EU law in Britain will end." That meant that the UK would have to leave the single market. It could not stay as close as possible to the EU economically - like Norway or Switzerland.

Hammond says that he had not been consulted about the speech or the policy:

"I didn't know. I think the prime minister felt that as a former remainer she needed to demonstrate her credentials by presenting quite an extreme version of Brexit. Some of the things that were being said were likely to have quite an impact outside the hall."

Senior EU figures were watching and concluded that the prime minister had outlined a series of undeliverable red lines.

The man who'd written the speech was May's powerful chief of staff Nick Timothy. A passionate leaver, he had also dreamed up "Brexit means Brexit" - a phrase that was much less empty than it seemed.

"I plead guilty to that phrase. It was one of the most irritating in British politics.

"Funnily enough it actually meant three different things. Firstly, that she understood that having been a remainer when the country voted to leave she would deliver on that mandate.

"It was [also] a warning to others - I think in particular in Parliament who were already showing signs of not really accepting the result - that Brexit must mean Brexit. Then at a third level that Brexit must meaningfully mean Brexit and couldn't be a kind of shadow membership."

Find out more

Click here to watch Panorama: Britain's Brexit Crisis on BBC One, 18 July at 21:00

In the same speech, May announced that she would soon begin the formal process of leaving the EU by triggering Article 50. Hammond believes this was a mistake, given that there had been no real debate in the government, let alone the country, about what Brexit should mean.

"With the benefit of hindsight, I can now see that that was wrong," he says. "The real issue is debating with ourselves what kind of Brexit Britain wants. And we should have done that before we triggered the process."

The chancellor says there was always going to be a tension between protecting the economy and "taking back control" of policies like immigration. It was a tension that was never fully resolved.

4. The first rule of politics - you have to be able to count

Getty Images The prime minister called the election because I think she knew the parliamentary arithmetic was already difficult

"... She hoped to improve her position and make it easier to deliver what people voted for in the referendum but actually the result made that job even more difficult."

Gavin Barwell lost his seat as a Conservative MP when Theresa May called a general election in June 2017. He was hired as her new chief of staff, replacing Nick Timothy - the man blamed by many for her decision to go to the polls. The election left her with no majority in the House of Commons.

"Those first few weeks were a pretty traumatic experience," says Barwell. "That was apparent from the first day I walked into No 10."

The US President Lyndon B Johnson said: "The first rule of politics - you have to be able to count."

In other words, leaders need to be sure that they have more people backing their policies than opposing them.

Image copyright Getty Images Image caption May with Arlene Foster, whose DUP party the prime minister turned to for support

The votes of Tory MPs alone would not now give May a majority. She turned to Northern Ireland's Democratic Unionist Party (DUP) for support. What she didn't do - until it was far too late - was to try to woo opposition MPs. That was what Ted Heath had done before he took Britain into the Common Market in 1973.

Incidentally, it was not just May's closest advisers and cabinet ministers who helped convince her to call an election. Allies of Jean-Claude Juncker, a former prime minister himself, admit that while he would never have advised her to call an election, he did tell her that having her own mandate would help her.

Juncker warned that a tiny majority in a House of Commons that was less enthusiastic about Brexit than the British public would cause real problems when she eventually needed MPs to ratify a Brexit deal with the EU.

5. The clock was always ticking

Getty Images I heard so many journalists and politicians in the UK speaking about this negotiation as an easy and very rapid negotiation - it was a huge surprise to me

"...The UK chose itself the date for leaving in March 2019. This is why every time I just recall the clock is ticking. Be careful eh?"

Again and again, Michel Barnier reminded British ministers that they would have just two years to reach agreement. It was clearly stated in Article 50 of the Lisbon Treaty that set the rules for how a country could leave the EU. It allowed Brussels to use time against the UK.

Senior figures in government have told me that the UK side misunderstood Barnier's real role. He was the public face of the negotiations and the politician who would keep the leaders of the EU's 27 countries on side.

Barnier's deputies did the real negotiating, alongside Martin Selmayr - the man whose nickname in Brussels is "the Monster" - who really decided what could and could not be agreed by the EU.

Selmayr explains the thinking behind the process for the Brexit negotiations, that would give the EU control not just of the timetable but also the agenda and the order [or sequencing] of the talks.

Image copyright Google Image caption Barnier with EU deputy chief negotiator for Brexit Sabine Weyand ahead of a meeting to discuss Article 50

"Brexit will always be a sad event because it's a divorce. First of all you separate the assets… the rights and duties that are stemming from 40 years of a very long and intense and close relationship. Then you see if you remain friends afterwards or if you can remain close friends afterwards."

In 2017, Brexit Secretary David Davis promised a long hot summer when he would fight the idea that the UK would have to agree the Brexit bill it owed - which would run into tens of billions of pounds - before any talks could begin on a future trading relationship with the EU.

In the event the fight never occurred. He claims that he was overruled by May:

"She felt pressurised, unconfident, maybe even insecure after the general election outcome. She gave away the fact that we were going to meet everything they wanted - money and citizens' rights and so on - and get nothing back in return."

6. No deal was an empty threat

Getty Images In any negotiation, you’ve got to be able to walk away. I’ve got to be able to say to you, ‘If this doesn’t work, we’ll leave anyway’ and you’ve got to believe it

David Davis never persuaded the rest of the cabinet, let alone the prime minister herself, to make the threat summed up in another of her oft-repeated phrases - "no deal is better than a bad deal" - appear credible.

"The Treasury in particular would always argue you can't frighten the horses," he says. "Don't talk about it publicly, don't say what needs to be done, don't do the public preparation."

Davis complains that the chancellor was so nervous of spooking business that he stopped the Brexit department sending out letters to tens of thousands of small businesses telling them to prepare for a no-deal Brexit.

Hammond counters that he was trying to reassure business to stay in the country and to keep investing, so the last thing he wanted was anything that would have the appearance of no deal.

"There was a tension at the beginning. We didn't want to send business a message that we're going to crash out of the EU and see businesses perhaps relocating - taking jobs out of the United Kingdom."

The official projections were clear. A no-deal Brexit would lead to 10% tariffs on car exports, and 40% tariffs on the sale of lamb, says Hammond, as well as potential chaos at Dover with the French being able to "dial up and dial down" the queues at will to make a political point.

Hammond was not alone. One of the top officials handling Brexit told ministers that threatening no deal was like taking the pin out of a grenade and holding it next to your own head.

When I asked Michel Barnier if May or her ministers had ever made a no deal threat behind closed doors, he replied emphatically, "No", before adding, "I think that the UK side, which is well informed and competent and knows the way we work on the EU side, knew from the very beginning that we've never been impressed by such a threat. It's not useful to use it."

Selmayr agreed. "I don't think it's ever a reality for anybody who is in a responsible position. It has consequences. It ruins your relationship for the future and I don't think anybody responsible on the UK side or the EU side has an interest in that," he said.

In fact, when I asked Selmayr if he thought the UK was prepared for that eventuality, he said he was "very certain" it was not.

"We have seen what has been prepared on our side of the border for a hard Brexit," he said. "We don't see the same level of preparation on the other side of the border.

7. The Irish border issue just wouldn't go away

PA What we needed was reassurance that no matter what happened in the Brexit negotiations, we weren’t going to see... a physical re-emergence of a border on the island of Ireland

"... That would be in many ways a symbol of the past of tragedy, of emotion, of terrorism, of murder."

It was not just in Brussels that Brexit was seen as a threat.

In Dublin, Simon Coveney - who is now Ireland's Tanaiste, or deputy head of government - says he feared that there would be a return to a hard Irish border unless the issue was addressed right at the beginning of the negotiations.

Other senior figures in the Irish government have told the BBC that they were concerned that Ireland could be "dragged out" of the EU by its bigger, richer neighbour. That is why the backstop - the issue which came to dog Brexit - was born.

After Brexit, the border between Northern Ireland and the Irish Republic would be the only land border between the EU and the UK. If peace was to continue, everyone agreed that there should be no border controls. However, the EU's desire to protect its single market would mean there had to be checks on certain goods such as farm animals and chemicals that crossed the border.

The argument went that a post-Brexit Britain might do a trade deal with Donald Trump's US and could agree to allow the import of chlorine-washed chicken or hormone-treated meat. Without a border, those banned goods could move from north to south and into the EU, undercutting European food standards and representing cheap and unfair competition to their farmers.

Image copyright Getty Images Image caption A No Border No Brexit sticker close to the Hands Across the Divide peace statue

Controls designed to enforce EU rules could become a target for paramilitaries and encourage smuggling which for years was key to the financing of terrorism.

If the UK followed EU rules and regulations, this wouldn't be a problem but Ireland and the EU demanded a guarantee - or a backstop - that whatever trade deal was eventually signed between the two sides there could never be a hard border.

Brexiteers saw this as a trap designed to keep the UK bound to EU rules and in a customs union. Talking to the BBC, the former Brexit Secretary Dominic Raab, sums up their fears:

"The idea that you could leave the EU, be successful and demonstrate that the EU perhaps wasn't all it was cut out to be was for them the thing that made [the EU] the most nervous. And the obvious answer to that was to try and lock the United Kingdom in to as many EU rules as possible without any say over them and without any means to escape from that regime, and that's the conundrum of the backstop."

Raab's predecessor David Davis agrees with this position:

"They needed a lever which put us in the wrong and them in the right, I think that's the way they saw it. [With] the Irish border there's a strong political, moral, sentimental argument... based on fiction really, but nevertheless that's how it's used."

In other words the backstop was as much about trade as it was about peace. It was as much about French determination to protect the single market as it was about Irish worries about a new source of conflict. One of May's closest allies told us it was the "operationalisation by Brussels of a French idea dressed in a green jersey".

So why did the prime minister sign up to it? Because the clock was ticking and because she'd agreed to the EU's sequencing of the talks. No backstop meant no progress to talking about trade.

What's more, Theresa May was desperate to get agreement to the Treasury's top priority, which was the demand from big business for an extra two years to adapt to Brexit - the so-called transition period.

Davis blames No 10 for agreeing to the backstop. "They signed up to the backstop because they were desperate to make progress. They basically had a loss of nerve."

When we put to Martin Selmayr that the deal was "swallow what you don't much like on Ireland, and get more time", he replies: "Absolutely."

8. The EU dreamed that the UK might change its mind

PA He was trying to seduce me over lunch... Martin [Selmayr] said, ‘Look, why don’t we have a deal whereby we just put all this on ice for five years. Let’s see how things go.'

"Let's get the UK involved with France and Germany. Let's see how the dust settles and let's talk about whether we can come to a new deal for Europe."

Britain's de facto deputy prime minister David Lidington reveals to Panorama that he was made that startling offer by Martin Selmayr. It followed a summit of world leaders at which EU heads found themselves on the same side as Theresa May in a series of arguments with President Trump.

Selmayr explains why the offer was made:

"All the other European leaders were left behind when he [Trump] took the helicopter and they looked each other in the eyes and also at Theresa May and they thought, 'At least we all agree with each other, we are the last bastion of the rules-based international system.' I think that led to many thinking, 'Well, if she comes back tomorrow and has thought again, we wouldn't mind'."

Donald Tusk once joked in public about the idea that Brexit could be reversed saying, "Who knows? You may say I'm a dreamer, but I'm not the only one." However, this is the first time it has been confirmed that an approach and an offer was made by the European Commission to put Brexit on ice.

The offer was rejected and some in the EU came to the view it would be better if the UK left - and left quickly. However, the scale of opposition Theresa May faced in Parliament meant others continued to believe and hope that there would be another referendum and Brexit would not happen. This made them less likely to compromise.

9. MPs couldn't agree on anything

Image copyright Number 10 Flickr Image caption May and members of her Cabinet meet at her country retreat Chequers

"The two big parties have been trying to outmanoeuvre each other on Brexit, and for a long time Brexit has been used by the opposition party as a way of trying to trigger a general election. For me, as somebody who loves Britain, who's lived there, who's studied there, who has family there, I think it's a tragedy quite frankly, that in the face of this huge decision that the British people have made, that the political system has not been able to unite behind a middle-ground position and unite the country."

Simon Coveney is scathing about the failure of the British Parliament and political system to achieve consensus on Brexit. It's a stark contrast with the unity which has been on show in Dublin.

He blames the opposition Labour Party as well as the Tories. The government's Chief Whip, Julian Smith, says that he has lost a lot of sleep as a result of trying - and failing - to get a deal through the House of Commons.

"I think that there was definitely a shift from some Brexiteers who, if you'd asked them three years ago, would they be happy with the prime minister's deal, they'd have bitten your arm off. They then, during the course of the last year, became, I think, increasingly concerned about different elements of it, seeing some form of threat behind many aspects of it, and there was a kind of purification process - they sort of wanted everything on day one."

The Tories were hopelessly divided over what sort of Brexit deal to pursue. When May finally proposed her "Chequers plan" she did it without ensuring that she had the support of David Davis, her Brexit secretary .

Her allies believe that if Davis had been offered another job, he would have taken it rather than quitting the Cabinet altogether. They believe that Boris Johnson might then have stayed in the government. As it was he became the figurehead for those wanting to "chuck Chequers" and, eventually, to chuck Theresa May as well.

The chief whip also blames the Speaker for blocking Brexit. John Bercow ruled that the government could not bring back its withdrawal agreement to the Commons after it had been defeated twice. By this time, even hardliners like Boris Johnson and Jacob Rees-Mogg were prepared to vote with the government. No 10 insiders claim that they had the basis of an agreement which could have got DUP support as well but the vote was never held.

"Parliament is and has been deadlocked for one simple reason," says Julian Smith. "Large groups of MPs have been prepared to gamble that they could force the outcome they wanted - a harder Brexit or another referendum or a general election - rather than backing Theresa May's deal."

10. It was all a terrible misunderstanding

Getty Images For Germany the EU is much, much more than a market, it’s their destiny

"If the only goal of the EU is this market obviously you could think that the German car industry could force the German government to comply with the demands coming out of London, but for Germany the EU is much, much more than a market. It's their destiny, it's not revisiting the horrors of history so even the car industry itself understands that this is fundamentally more important than selling cars to the United Kingdom."

EU leaders such as Frans Timmermans believe that British politicians do not understand the idealism and the history which underlies the European project. He says that "continental Europeans" do not see the EU in the same way as the United Kingdom - "as a market".

Brexiteers like Boris Johnson don't dispute the history but they do doubt that the leaders of any country would willingly harm their own economies. He has said in public that EU countries will want to sell us their cars or cheese or even Prosecco.

Did that claim infuriate Timmermans?

"Yes it did, also, perhaps I'm being a bit harsh but it's about time we became a bit harsh also because I'm not sure he [Johnson] was being genuine, I always have the impression he's playing games."

Image copyright Getty Images Image caption German Chancellor Angela Merkel meets May in Berlin to discuss Brexit, ahead of a summit of European Union leaders in Brussels

David Lidington - a lifelong pro-European - agrees that the EU has always seen itself as a political project but says it takes two to create a misunderstanding. He says that EU leaders have too often dismissed British demands as driven purely by short-term political pressures rather than principle:

"They thought Tories were simply pandering to UKIP or the DUP and never understood that Euroscepticism, a desire for sovereignty, support for the Union were real forces that any political leader and party would have to address."

Those misunderstandings have dogged the Brexit negotiations as both sides have miscalculated how the other side will react.

What has not been tested yet is whether the credible threat of no deal, a refusal to compromise on the Irish border and a willingness to withhold the £39bn divorce bill which Britain has agreed to pay will improve or destroy the chances of getting a deal.

We're about to find out.

Additional research and reporting by Britain's Brexit Crisis producer Max Stern