import React, { useEffect, useState } from 'react';
import {
  useAppDispatch,
  useAuthCache,
  useML,
  useQuerybuilderGraph,
  useQuerybuilderSettings,
  useSessionCache,
} from '@/lib/data-access/store';
import { addError, setCurrentTheme } from '@/lib/data-access/store/configSlice';
import { resetGraphQueryResults, queryingBackend } from '@/lib/data-access/store/graphQueryResultSlice';
import { FrozenOverlay, Resizable } from '@/lib/components/layout';
import { DashboardAlerts } from '@/lib/data-access/security/dashboardAlerts';
import { EventBus } from '@/lib/data-access/api/eventBus';
import { URLParams, setParam } from '@/lib/data-access/api/url';
import { VisualizationPanel } from '@/lib/vis';
import { QueryBuilder } from '@/lib/querybuilder';
import { SideNavTab, Sidebar } from '@/lib/sidebar';
import { InspectorPanel } from '@/lib/inspector';
import { SearchBar } from '@/lib/sidebar/search/SearchBar';
import { Schema } from '@/lib/schema/panel';
import { InsightDialog } from '@/lib/insight-sharing';
import { wsQueryRequest } from '@/lib/data-access/broker';
import { ErrorBoundary } from '@/lib/components/errorBoundary';
import { Onboarding } from './app/onboarding/onboarding';
import { Navbar } from './app/navbar/navbar';
import { QueryMultiGraph } from 'ts-common';

export type App = {
  load?: string;
};

export function App(props: App) {
  const auth = useAuthCache();
  const query = useQuerybuilderGraph() as QueryMultiGraph;
  const ml = useML();
  const session = useSessionCache();
  const dispatch = useAppDispatch();
  const [monitoringOpen, setMonitoringOpen] = useState<boolean>(false);

  const rerunQuery = () => {
    if (session?.currentSaveState && query) {
      if (query.nodes.length === 0) {
        dispatch(resetGraphQueryResults());
      } else {
        dispatch(queryingBackend());
        wsQueryRequest({ saveStateID: session.currentSaveState, ml });
      }
    }
  };

  useEffect(() => {
    if (props.load) {
      setParam(URLParams.saveState, props.load);
    }
  }, [props]);

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
    dispatch(setCurrentTheme(event.matches));
  });

  const [authCheck, setAuthCheck] = useState(false);
  const [tab, setTab] = useState<SideNavTab>('Schema');
  // const [visFullSize, setVisFullSize] = useState<boolean>(false);

  return (
    <div className="h-screen w-screen overflow-clip">
      <EventBus
        onRunQuery={rerunQuery}
        onAuthorized={() => {
          setAuthCheck(true);
        }}
      />
      {authCheck && (
        <>
          <Onboarding />
          <DashboardAlerts />
          <div className={'h-screen w-screen '}>
            <div className="flex flex-col h-screen max-h-screen relative">
              <aside className="absolute w-full h-12">
                <Navbar />
              </aside>
              <main className="grow flex flex-row h-screen pt-12">
                <Sidebar
                  onTab={tab => setTab(tab)}
                  tab={tab}
                  openMonitoringDialog={() => {
                    setMonitoringOpen(!monitoringOpen);
                  }}
                />
                <InsightDialog open={monitoringOpen} onClose={() => setMonitoringOpen(!monitoringOpen)} />
                <Resizable divisorSize={3} horizontal={true} defaultProportion={0.85} maxProportion={0.85}>
                  <Resizable divisorSize={3} horizontal={true} defaultProportion={0.33}>
                    {tab !== undefined ? (
                      <div className="flex flex-col w-full h-full">
                        {tab === 'Search' && (
                          <ErrorBoundary
                            fallback={<div>Something went wrong</div>}
                            onError={() => dispatch(addError('Something went wrong while trying to load the search bar'))}
                          >
                            <SearchBar onRemove={() => setTab(undefined)} />
                          </ErrorBoundary>
                        )}
                        {tab === 'Schema' && (
                          <ErrorBoundary
                            fallback={<div>Something went wrong</div>}
                            onError={() => dispatch(addError('Something went wrong while trying to load the schema panel'))}
                          >
                            <Schema auth={authCheck} onRemove={() => setTab(undefined)} />
                          </ErrorBoundary>
                        )}
                      </div>
                    ) : null}

                    <Resizable divisorSize={3} horizontal={false}>
                      <ErrorBoundary
                        fallback={<div>Something went wrong</div>}
                        onError={() => dispatch(addError('Something went wrong while trying to load the visualization panel'))}
                      >
                        <VisualizationPanel
                          fullSize={() => {
                            // setVisFullSize(!visFullSize);
                            // tab === undefined && setTab('Schema');
                            // tab !== undefined && setTab(undefined);
                          }}
                        />
                      </ErrorBoundary>
                      <ErrorBoundary
                        fallback={<div>Something went wrong</div>}
                        onError={() => dispatch(addError('Something went wrong while trying to load the query builder'))}
                      >
                        <QueryBuilder onRunQuery={rerunQuery} />
                      </ErrorBoundary>
                    </Resizable>
                  </Resizable>
                  <InspectorPanel />
                </Resizable>
              </main>
            </div>
          </div>
          <FrozenOverlay>
            {!auth.authentication?.authenticated && <span>Not Authenticated</span>}
            {!auth.authorization.savestate?.W && !session.currentSaveState && (
              <span>Viewer account not authorized. Please load a shared exploration.</span>
            )}
          </FrozenOverlay>
        </>
      )}
    </div>
  );
}

export default App;