import { ReactElement, useContext, useEffect, useState } from "react";

import SignInView from "./components/sign-in";
import { LoadingView } from "./components/loading-view";
import { OnboardingSteps } from "./components/onboarding-steps";
import { ApiContext } from "./context";
import { ColorTheme } from "./types/shared-types";

interface AppProps {
	themes: ColorTheme[];
	currentThemeId: string;
	portalUrl?: string;
}

type ActiveView = "sign-in" | "welcome" | "onboarding" | "finishing" | "blank";

export function App({
	themes,
	currentThemeId,
	portalUrl,
}: AppProps): ReactElement {
	const [activeView, setActiveView] = useState<ActiveView>("blank");

	const {
		close,
		needsSignIn,
		needsOnboarding,
		startOnboarding,
		completeOnboarding,
	} = useContext(ApiContext);

	const themeType =
		themes.find((theme) => theme.id === currentThemeId)?.type || "dark";

	// This effect determines the initial view
	useEffect(() => {
		void needsSignIn().then((signInNeeded) => {
			if (signInNeeded) {
				setActiveView("sign-in");
			} else {
				startOnboarding();
				setActiveView("onboarding");
			}
		});
	}, [needsSignIn, startOnboarding]);

	async function onSignInComplete() {
		if (await needsOnboarding()) {
			setActiveView("welcome");
		} else {
			close();
		}
	}

	function onWelcomeComplete() {
		startOnboarding();
		setActiveView("onboarding");
	}

	function onOnboardingComplete() {
		setActiveView("finishing");
	}

	async function onFinishingComplete() {
		await completeOnboarding();
		close();
	}

	return (
		<div
			className={`vscode-${themeType} w-full h-full relative overflow-hidden text-[var(--vscode-editor-foreground)] bg-[var(--vscode-background)] select-text`}
		>
			{activeView === "sign-in" && (
				<SignInView
					themeType={themeType}
					onSignInComplete={onSignInComplete}
					portalUrl={portalUrl}
				/>
			)}
			{activeView === "welcome" && (
				<LoadingView
					themeType={themeType}
					onCompleted={onWelcomeComplete}
					minDurationSeconds={2}
					title="Success!"
					subTitle="You logged in, let's get started."
				/>
			)}
			{activeView === "onboarding" && (
				<OnboardingSteps
					themeType={themeType}
					onCompleted={onOnboardingComplete}
					themes={themes}
					currentThemeId={currentThemeId}
				/>
			)}
			{activeView === "finishing" && (
				<LoadingView
					themeType={themeType}
					onCompleted={onFinishingComplete}
					minDurationSeconds={2}
					title="Loading"
					subTitle="Setting up your IDE..."
				/>
			)}
		</div>
	);
}
