import { useContext } from "react";
import { AccountDashboardApiContext } from "../../context/account-dashboard-api-context";
import { UsageLimits } from "../../types/account-dashboard-types";
import { logError } from "../../utils/logger";

const UPGRADE_URL = "https://app.kiro.dev/settings/account#upgrade";

interface PlanActionsProps {
	usageLimits: UsageLimits | null;
	onClose: () => void;
}

export function PlanActions({
	usageLimits,
	onClose,
}: PlanActionsProps): React.JSX.Element {
	const { getPaymentPortalUrl, openExternalLink } = useContext(
		AccountDashboardApiContext,
	);

	const shouldShowUpgradeplanButton =
		usageLimits?.subscriptionInfo.subscriptionManagementTarget === "PURCHASE";

	const handleUpgradePlan = async () => {
		try {
			await openExternalLink(UPGRADE_URL);
			onClose();
		} catch (error) {
			logError("Failed to open upgrade page", error as Error);
		}
	};

	const handleManagePlanPortal = async () => {
		try {
			const response = await getPaymentPortalUrl();
			if (response.error) {
				logError(`Failed to get payment portal URL: ${response.error}`);
				return;
			}
			if (response.data) {
				await openExternalLink(response.data);
				onClose();
			}
		} catch (error) {
			logError("Failed to manage plan portal", error as Error);
		}
	};

	const handleContactSupport = async () => {
		try {
			await openExternalLink("https://app.kiro.dev/settings/account#support");
		} catch (error) {
			logError("Failed to open billing support link", error as Error);
		}
	};

	// Reusable plan button component
	const PlanButton = ({
		title,
		onClick,
	}: {
		title: string;
		onClick: () => void;
	}) => (
		<button onClick={onClick} className="kiro-button kiro-button-primary">
			{title}
		</button>
	);

	return (
		<div className="kiro-account-dashboard-section">
			{shouldShowUpgradeplanButton ? (
				<PlanButton title={"Upgrade Plan"} onClick={handleUpgradePlan} />
			) : (
				<PlanButton title={"Manage Plan"} onClick={handleManagePlanPortal} />
			)}

			<div className="kiro-modal-link">
				<a onClick={handleContactSupport}>Contact Billing Support</a>
			</div>
		</div>
	);
}
