import { useContext } from "react";
import { UsageSummary } from "./usage-summary";
import { OverageSettings } from "./overage-settings/overage-settings";
import { PlanActions } from "./plan-actions";
import { Modal, ModalHeader, ModalSectionContainer } from "../modal";
import { AccountDashboardApiContext } from "../../context/account-dashboard-api-context";
import { useUsageLimits } from "../../hooks/useUsageLimits";
import { ModalLoadingSkeleton } from "../modal/modal-loading-skeleton";
import { ProfileLink } from "./profile-link";
import { useCurrentProfile } from "../../hooks/use-current-profile";
import { useSignOut } from "../../hooks/use-sign-out";
import { UsageSummarySkeleton } from "./usage-summary/usage-summary-skeleton";
import { OverageSettingsSkeleton } from "./overage-settings/overage-settings-skeleton";
import { UserInfoView } from "./user-info-view";
import { SignInPrompt } from "./sign-in-prompt";
import { UserInfo } from "../../types/account-dashboard-types";
import { ModalErrorBanner } from "../modal/modal-error-banner";

export function AccountDashboardPage(): React.JSX.Element {
	const { close, showProfileSelector } = useContext(AccountDashboardApiContext);
	const {
		usageLimits,
		loading: isLoadingUsageLimits,
		error: usageLimitError,
	} = useUsageLimits();
	const {
		currentProfile,
		profiles,
		isLoading: isLoadingProfiles,
		error: profileError,
	} = useCurrentProfile();
	const { onSignOut, isSigningOut } = useSignOut();

	const userInfoFromError: UserInfo = {
		isLoggedIn: usageLimitError?.isLoggedIn ?? false,
		provider: usageLimitError?.provider,
	};
	const userInfo = usageLimits?.userInfo ?? userInfoFromError ?? {};
	const isLoading = isLoadingUsageLimits || isLoadingProfiles;
	const isLoggedIn = userInfo?.isLoggedIn ?? false;
	const isEnterpriseUser = userInfo?.provider?.id === "Enterprise" || userInfo?.provider?.id === 'ExternalIdp';
	const hasMultipleProfiles = (profiles ?? []).length > 1;
	const shouldShowOveragesSection =
		isEnterpriseUser || usageLimits?.subscriptionInfo.overageCapable;
	const shouldPlanActions = !isEnterpriseUser;
	// For now just prioritize one over the other
	const error = usageLimitError || profileError;
	const isFeatureNotSupported =
		error?.statusCode === 403 && error.reason === "FEATURE_NOT_SUPPORTED";

	const getTitle = () => {
		if (!userInfo) {
			return;
		}

		if (isEnterpriseUser) {
			return "Kiro Enterprise";
		}

		return userInfo.email || "Kiro";
	};

	const getSubtitle = () => {
		if (!userInfo) {
			return;
		}

		if (hasMultipleProfiles) {
			return (
				<ProfileLink
					currentProfile={currentProfile}
					onClick={showProfileSelector}
				/>
			);
		}

		if (!isEnterpriseUser) {
			return <UserInfoView userInfo={userInfo} />;
		}
	};

	const getAction = () => {
		if (isLoggedIn) {
			return {
				label: "Sign Out",
				disabled: isSigningOut,
				onClick: onSignOut,
			};
		}
	};

	if (isLoading) {
		return (
			<Modal>
				<ModalHeader withGhost action={getAction()} />
				<ModalLoadingSkeleton>
					<ModalSectionContainer showSeparatorBefore>
						<UsageSummarySkeleton />
					</ModalSectionContainer>
					<ModalSectionContainer showSeparatorBefore>
						<OverageSettingsSkeleton />
					</ModalSectionContainer>
				</ModalLoadingSkeleton>
			</Modal>
		);
	}

	return isLoggedIn ? (
		<Modal>
			<ModalHeader
				withGhost
				title={getTitle()}
				subTitle={getSubtitle()}
				action={getAction()}
			/>
			{error && !isFeatureNotSupported && (
				<ModalSectionContainer showSeparatorBefore>
					<ModalErrorBanner error={error.message} />
				</ModalSectionContainer>
			)}
			{!isFeatureNotSupported && (
				<>
					<ModalSectionContainer showSeparatorBefore>
						<UsageSummary
							usageLimits={usageLimits}
							isEnterpriseUser={isEnterpriseUser}
						/>
					</ModalSectionContainer>
					{shouldShowOveragesSection && (
						<ModalSectionContainer showSeparatorBefore>
							<OverageSettings
								usageLimits={usageLimits}
								isEnterpriseUser={isEnterpriseUser}
							/>
						</ModalSectionContainer>
					)}
					{shouldPlanActions && (
						<ModalSectionContainer showSeparatorBefore>
							<PlanActions usageLimits={usageLimits} onClose={close} />
						</ModalSectionContainer>
					)}
				</>
			)}
		</Modal>
	) : (
		<Modal>
			<ModalSectionContainer>
				<SignInPrompt />
			</ModalSectionContainer>
		</Modal>
	);
}
