import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";

import Client, { IAuth } from "./client/Client";
import { AccountIdMap, IAccount, IMailbox } from "./client/types";
import AppLayout from "./AppLayout";
import AuthModal from "./AuthModal";
import React from "react";

interface ILocation {
	accountId: string;
}

type AppState = {
	auth: IAuth;
	account: IAccount | null;
	accounts: AccountIdMap;
	location: ILocation;
	mailbox: IMailbox | null;
};

type AppProps = {};

class App extends React.Component<AppProps, AppState> {
	account(): IAccount | null {
		return this.client.account(this.state.location.accountId);
	}
	client: Client = new Client();
	state: AppState = {
		account: null,
		accounts: {},
		auth: { email: "", password: "" },
		location: { accountId: "" },
		mailbox: null,
	};

	onHashChange() {
		console.log(window.location.hash);
		const hash = window.location.hash.substring(1);
		this.setState({
			...this.state,
			account: this.account(),
			location: { accountId: hash },
		});
	}

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

	onMailboxSelect(mailboxId: string) {
		console.log("Mailbox", mailboxId);
	}

	// Load up auth credentials from the local store
	loadAuth() {
		const data = localStorage.getItem("auth");
		if (!data) return;
		const auth = JSON.parse(data);
		this.setState({
			...this.state,
			auth: auth,
		});
		this.client.ensureLogin(auth);
	}

	componentDidMount() {
		window.addEventListener(
			"hashchange",
			() => {
				this.onHashChange();
			},
			false,
		);
		this.loadAuth();
		this.onHashChange();
		this.client.onChange(() => {
			this.setState({
				...this.state,
				account: this.account(),
				accounts: this.client.state.session
					? this.client.state.session.accounts
					: {},
			});
		});
	}

	componentWillUnmount() {
		window.removeEventListener(
			"hashchange",
			() => {
				this.onHashChange();
			},
			false,
		);
	}

	render() {
		return (
			<div className="App">
				<AppLayout
					account={this.state.account}
					accounts={this.state.accounts}
					client={this.client}
					mailbox={this.state.mailbox}
					onMailboxSelect={this.onMailboxSelect}
				/>
				<AuthModal
					show={this.client.state.session == null}
					onLogin={this.onLogin}
				></AuthModal>
			</div>
		);
	}
}

export default App;
