import type { DeviceFlowParams } from 'navigraph/auth';
import { QRCodeSVG } from 'qrcode.react';
import { useState } from 'react';
import { ProcedureSelect } from './components//ProcedureSelect';
import { Map } from './components/Map';
import { Sidebar } from './components/Sidebar';
import { useNavigraphAuth } from './contexts/NavigraphAuth/NavigraphAuthContext';
import Parser from './parser/parser';

const parser = await Parser.instance();

function App() {
  const [selectedAirport, setSelectedAirport] = useState<Airport>();
  const [selectedRunway, setSelectedRunway] = useState<Runway>();
  const [selectedTerminal, setSelectedTerminal] = useState<Terminal>();
  const [transitions, setTransitions] = useState<Procedure[]>([]);
  const [params, setParams] = useState<DeviceFlowParams | null>(null);
  const [selectedTransition, setSelectedTransition] = useState<Procedure>();
  const [selectedChart, setSelectedChart] = useState<Chart>();

  const { user, signIn, initialized } = useNavigraphAuth();

  const handleSignIn = () => signIn((p) => setParams(p));

  return (
    <>
      {!user ? (
        <div className="flex min-h-dvh w-full">
          {!initialized && <div>Loading...</div>}

          {initialized && !params && !user && <button onClick={handleSignIn}>Sign in</button>}

          {params?.verification_uri_complete && !user && (
            <>
              <QRCodeSVG value={params.verification_uri_complete} size={250} />
              <a href={params.verification_uri_complete} target="_blank" rel="noreferrer">
                Open sign in page
              </a>
            </>
          )}
        </div>
      ) : (
        <div className="flex h-dvh w-dvw">
          {selectedAirport && selectedRunway && selectedTerminal ? (
            <Sidebar
              airport={selectedAirport}
              runway={selectedRunway}
              terminal={selectedTerminal}
              transitions={transitions}
              transition={selectedTransition}
              chart={selectedChart}
              setTransition={setSelectedTransition}
              setChart={setSelectedChart}
              backAction={() => {
                setSelectedTerminal(undefined);
                setSelectedChart(undefined);
                setTransitions([]);
                setSelectedTransition(undefined);
              }}
            />
          ) : (
            <ProcedureSelect
              selectedAirport={selectedAirport}
              selectedRunway={selectedRunway}
              selectedTerminal={selectedTerminal}
              setSelectedAirport={setSelectedAirport}
              setSelectedRunway={setSelectedRunway}
              setSelectedTerminal={setSelectedTerminal}
              handleSelection={(selectedTransitions) => {
                let _transitions = selectedTransitions
                  .map((transition) => ({
                    name: transition,
                    data: parser.parse(selectedRunway!, transition),
                  }))
                  .filter(
                    (transition) =>
                      !transition.name.startsWith('RW') || transition.name === `RW${selectedRunway?.Ident}`
                  );

                if (_transitions.length > 1)
                  _transitions = _transitions.filter((transition) => transition.name !== 'ALL');
                setTransitions(_transitions);
                setSelectedTransition(_transitions[0]);
                setSelectedChart(undefined);
              }}
            />
          )}
          <Map
            airport={selectedAirport}
            chart={selectedChart}
            procedures={selectedTransition ? [selectedTransition] : []}
          />
        </div>
      )}
    </>
  );
}

export default App;
