import { useEffect, useState } from "react";
import { parse } from "@aws-sdk/util-arn-parser";
import { useProfiles } from "../../hooks/use-profiles";
import { ModalLoadingSkeleton } from "../modal/modal-loading-skeleton";
import { ModalErrorBanner } from "../modal/modal-error-banner";
import {
	Modal,
	ModalAction,
	ModalHeader,
	ModalSectionContainer,
} from "../modal";
import { ProfileSkeleton } from "./profile-skeleton";
import { ProfileOption } from "./profile-option";
import { ProfileWithUsageLimits } from "../../types/profile-selector-types";
import { ModalLoadingSpinner } from "../modal/modal-loading-spinner";

interface ProfileSelectorProps {
	shouldAutoSelect?: boolean;
}

export function ProfileSelector({
	shouldAutoSelect,
}: ProfileSelectorProps): React.JSX.Element {
	const {
		currentProfile,
		profiles,
		error,
		isLoading,
		onBack,
		onSubmitSelection,
	} = useProfiles({ shouldAutoSelect });
	const [selectedProfile, setSelectedProfile] =
		useState<ProfileWithUsageLimits>();

	// If shouldAutoSelect is true, the selector will take care of auto selection if user has only
	// one profile. This means that the inital load cannot assume the full selector will be necessary,
	// so simplifed loading elements will be presented as well.
	const isSimpleLoading = isLoading && shouldAutoSelect;

	useEffect(() => {
		if (!selectedProfile && profiles?.length) {
			const profile = currentProfile
				? profiles.find(({ arn }) => currentProfile.arn === arn)
				: profiles[0];
			setSelectedProfile(profile);
		}
	}, [currentProfile, selectedProfile, profiles]);

	const handleSubmitSelection = () => {
		if (!selectedProfile) {
			return;
		}
		onSubmitSelection(selectedProfile);
	};

	const getLoadingElement = () => {
		return shouldAutoSelect ? (
			<ModalLoadingSpinner label="Setting up your profile..." />
		) : (
			<ModalLoadingSkeleton>
				<ProfileSkeleton />
			</ModalLoadingSkeleton>
		);
	};

	return (
		<Modal>
			{!isSimpleLoading && (
				<ModalHeader
					title="Choose a Kiro Profile"
					subTitle="Your account has access to Kiro from multiple profiles. You can change profiles at any time."
					withGhost
					onBack={onBack}
				/>
			)}
			{error && (
				<ModalSectionContainer showSeparatorBefore>
					<ModalErrorBanner error={error.message} />
				</ModalSectionContainer>
			)}
			<ModalSectionContainer showSeparatorBefore>
				<div className="kiro-profile-selector-content">
					{isLoading ? (
						getLoadingElement()
					) : (
						<>
							<div className="kiro-profile-options">
								{profiles?.map((profile) => {
									const { arn, name, subscriptionName, usages } = profile;
									const { region, accountId } = parse(arn);
									return (
										<ProfileOption
											accountId={accountId}
											name={name}
											region={region}
											subscriptionName={subscriptionName}
											usages={usages}
											isSelected={arn === selectedProfile?.arn}
											onClick={() => {
												setSelectedProfile(profile);
											}}
										/>
									);
								})}
							</div>
						</>
					)}
					{!isSimpleLoading && (
						<ModalAction
							label="Use profile"
							disabled={isLoading}
							onClick={handleSubmitSelection}
						/>
					)}
				</div>
			</ModalSectionContainer>
		</Modal>
	);
}
