import { useContext } from "react";
import { AccountDashboardApiContext } from "../../../context/account-dashboard-api-context";
import { UsageLimits } from "../../../types/account-dashboard-types";
import {
	getExtraCreditPackages,
	getVisibleExtraCreditPackages,
	MAX_VISIBLE_EXTRA_CREDIT_PACKAGES,
} from "../../../utils/subscription-utils";
import { logError } from "../../../utils/logger";
import { ExtraCreditItem } from "./extra-credit-item";

const BUY_CREDITS_URL = "https://app.kiro.dev/settings/account";
const VIEW_ALL_URL = "https://app.kiro.dev/settings/account";

interface ExtraCreditsProps {
	usageLimits: UsageLimits | null;
}

/**
 * Renders the "Additional credits" section shown when the prepaid-credits
 * feature is enabled. Lists each purchased credit package with its individual
 * usage, sorted with active packs on top and exhausted packs at the bottom.
 *
 * When the user has more than 5 packs, only 5 are shown and a "view all"
 * link appears next to the header.
 */
export function ExtraCredits({
	usageLimits,
}: ExtraCreditsProps): React.JSX.Element {
	const { openExternalLink } = useContext(AccountDashboardApiContext);
	const allPackages = getExtraCreditPackages(usageLimits);
	const visiblePackages = getVisibleExtraCreditPackages(allPackages);
	const totalCount = allPackages.length;
	const hasOverflow = totalCount > MAX_VISIBLE_EXTRA_CREDIT_PACKAGES;

	const handleAddCredits = async () => {
		try {
			await openExternalLink(BUY_CREDITS_URL);
		} catch (error) {
			logError("Failed to open extra credit purchase page", error as Error);
		}
	};

	const handleViewAll = async () => {
		try {
			await openExternalLink(VIEW_ALL_URL);
		} catch (error) {
			logError("Failed to open credits page", error as Error);
		}
	};

	return (
		<div className="kiro-account-dashboard-section kiro-extra-credits">
			<div className="kiro-account-dashboard-row">
				<span className="kiro-account-dashboard-label">
					Additional credits
				</span>
				{hasOverflow && (
					<span className="kiro-extra-credits-overflow">
						(showing {MAX_VISIBLE_EXTRA_CREDIT_PACKAGES} of {totalCount} —{" "}
						<a
							className="kiro-extra-credits-overflow-link"
							onClick={handleViewAll}
						>
							view all
						</a>
						)
					</span>
				)}
			</div>
			<div className="kiro-extra-credits-list">
				{visiblePackages.map((item, index) => (
					<ExtraCreditItem key={`extra-credit-item-${index}`} item={item} />
				))}
				<div className="kiro-modal-link kiro-extra-credits-buy">
					<a onClick={handleAddCredits}>Add credits</a>
				</div>
			</div>
		</div>
	);
}
