import React, { PropsWithChildren, useContext, useEffect, useState } from 'react';
import './App.css';
import { Client } from './client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { DesignPage } from './views/Design/Design';
import { GmView } from './views/GmView/GmView';
import { WebsocketProvider } from './components/WebsocketProvider';
import { PlayerView } from './views/PlayerView/PlayerView';
import { Admin } from './views/Admin/Admin';
import Candela from './plugins/Candela';
import { Authentication } from './views/Authentication/Authentication';
import { StateContext, StateProvider } from './providers/StateProvider/StateProvider';

const TEST_CHARSHEET_UUID = "12df9c09-1f2f-4147-8eda-a97bd2a7a803";

interface AppProps {
    client: Client;
}

const CandelaCharsheet = ({ client }: { client: Client }) => {
    let [sheet, setSheet] = useState(undefined);
    useEffect(
        () => { client.charsheet(TEST_CHARSHEET_UUID).then((c) => setSheet(c)); },
        [client, setSheet]
    );

    return sheet ? <Candela.CharsheetElement sheet={sheet} /> : <div> </div>
}

interface AuthedViewProps {
    client: Client;
}

const AuthedView = ({ client, children }: PropsWithChildren<AuthedViewProps>) => {
    const [state, manager] = useContext(StateContext);
    return (
        <Authentication onAdminPassword={(password) => {
            manager.setAdminPassword(password);
        }} onAuth={(username, password) => manager.auth(username, password)}>
            {children}
        </Authentication>
    );
}

const App = ({ client }: AppProps) => {
    console.log("rendering app");
    const [websocketUrl, setWebsocketUrl] = useState<string | undefined>(undefined);

    useEffect(() => {
        client.registerWebsocket().then((url) => setWebsocketUrl(url))
    }, [client]);

    let router =
        createBrowserRouter([
            {
                path: "/",
                element: <StateProvider client={client}><AuthedView client={client}> <PlayerView client={client} /> </AuthedView> </StateProvider>
            },
            {
                path: "/gm",
                element: websocketUrl ? <WebsocketProvider websocketUrl={websocketUrl}> <GmView client={client} /> </WebsocketProvider> : <div> </div>
            },
            {
                path: "/admin",
                element: <Admin client={client} />
            },
            {
                path: "/candela",
                element: <CandelaCharsheet client={client} />
            },
            {
                path: "/design",
                element: <DesignPage />
            }
        ]);
    return (
        <div className="App">
            <RouterProvider router={router} />
        </div>
    );
}

export default App;
