import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import * as base64 from "base-64";
import { Client } from "jmap-client-ts";
import { ISession } from "jmap-client-ts/lib/types";
import { FetchTransport } from "jmap-client-ts/lib/utils/fetch-transport";

import AccountList from "./AccountList";
import AuthModal from "./AuthModal";
import React, { useEffect, useState } from "react";

interface IAuth {
	email: string;
	password: string;
}

interface IAppState {
	auth: IAuth;
	client: Client | null;
	session: ISession | null;
}

const App = () => {
	const [state, setInternalState] = useState<IAppState>({
		auth: { email: "", password: "" },
		client: null,
		session: null,
	});

	// When the user provides credentials
	const onLogin = (email: string, password: string) => {
		// Store the provided credentials for now
		state.auth.email = email;
		state.auth.password = password;
		state.client = null;
		setInternalState(state);
		localStorage.setItem("auth", JSON.stringify(state.auth));
		doLogin(state.auth);
	};

	// Make the request to get system metadata
	const doLogin = (auth: IAuth) => {
		const domain = auth.email.split("@")[1];
		const well_known_url = "https://" + domain + "/.well-known/jmap";
		const basic_auth =
			"Basic " + base64.encode(auth.email + ":" + auth.password);

		state.client = new Client({
			accessToken: "fake token",
			httpHeaders: { Authorization: basic_auth },
			sessionUrl: well_known_url,
			transport: new FetchTransport(fetch.bind(window)),
		});

		state.client
			.fetchSession()
			.then(() => {
				console.log("Session recieved");
				if (state.client) {
					state.session = state.client.getSession();
					setInternalState({
						...state,
						session: state.client.getSession(),
					});
				}
			})
			.catch((error) => console.error(error));

		return;
	};

	const loadAuth = () => {
		const data = localStorage.getItem("auth");
		if (!data) return;
		const auth = JSON.parse(data);
		state.auth = auth;
		if (state.client == null) {
			console.log("NULL STATE.client");
			doLogin(state.auth);
			return;
		}
	};

	useEffect(() => {
		loadAuth();
	}, []);

	return (
		<div className="App">
			{state && state.auth ? (
				<AccountList accounts={state.session ? state.session.accounts : {}} />
			) : (
				<AuthModal onLogin={onLogin}></AuthModal>
			)}
		</div>
	);
};

export default App;
