import { KiroButton } from "../kiro-button";
import { OnboardingStepContainer } from "./onboarding-step-container";
import { useOnboardingState } from "../../hooks";
import { OnboardingStepStatus } from "./onboarding-step-status";
import { OnboardingStepState } from "../../types/shared-types";

interface OnboardingStepSettingsProps {
	onNext: () => void;
	onComplete: () => void;
}

export function OnboardingStepSettings({
	onNext,
	onComplete,
}: OnboardingStepSettingsProps): React.JSX.Element {
	const {
		runOnboardingStep: runOnboardingSettingsStep,
		onboardingState: onboardingSettingsState,
	} = useOnboardingState("import-settings");

	const {
		runOnboardingStep: runOnboardingExtensionsStep,
		onboardingState: onboardingExtensionsState,
	} = useOnboardingState("install-extensions");

	async function onImportSettings(): Promise<void> {
		const newState = await runOnboardingSettingsStep({ minDuration: 0 });
		if (newState.status === "complete") {
			const newExtensionsState = await runOnboardingExtensionsStep({
				minDuration: 500,
				input: {
					themeName: newState["importedThemeName"],
				},
			});
			if (newExtensionsState.status === "complete") {
				onComplete();
			}
		}
	}

	const messages = [
		...(onboardingSettingsState?.messages || []),
		...(onboardingExtensionsState?.messages || []),
	];

	const statuses = [
		onboardingSettingsState.status,
		onboardingExtensionsState.status,
	];

	let combinedStatus: OnboardingStepState["status"] = "loading";
	if (onboardingExtensionsState.status === "complete") {
		combinedStatus = "complete";
	} else if (statuses.every((status) => status === "incomplete")) {
		combinedStatus = "incomplete";
	} else if (statuses.some((status) => status === "error")) {
		combinedStatus = "error";
	}

	return (
		<OnboardingStepContainer
			title="Import configuration"
			body={
				<div className="flex flex-col gap-5 items-center">
					<p>
						Migrate extensions, settings and keybindings. Get instantly started
						with Kiro using familiar VS Code configurations.
					</p>
					<p>
						Only extensions available on Open VSX can be imported. Extensions
						are loaded in the background, so you can continue with onboarding
						while they install.
					</p>
					<OnboardingStepStatus
						logMessages={messages}
						status={combinedStatus}
						completeTitle="Import complete"
					/>
				</div>
			}
			controls={
				combinedStatus !== "complete" ? (
					<>
						<KiroButton
							loading={combinedStatus === "loading"}
							onClick={onImportSettings}
						>
							Import from VS Code
						</KiroButton>
						<KiroButton onClick={onNext} style="secondary">
							{combinedStatus === "loading" ? "Next" : "Skip"}
						</KiroButton>
					</>
				) : (
					<KiroButton onClick={onNext} style="secondary">
						Next
					</KiroButton>
				)
			}
		/>
	);
}
