import { useContext, useMemo, memo } from "react";
import { ColorTheme } from "../../types/shared-types";
import { SubscriptionPlansApiContext } from "../../context/subscription-plans-api-context";
import { transformSubscriptionPlansToUI } from "../../utils/subscription-plan-transformer";
import { useSubscriptionPlans } from "../../hooks/useSubscriptionPlans";
import { LoadingSkeleton } from "./loading-skeleton";
import { ErrorBanner } from "./error-banner";
import { PlanCard } from "./plan-card";

interface SubscriptionPlansPageProps {
	themes: ColorTheme[];
	currentThemeId: string;
}

interface PageWrapperProps {
	themeType: string;
	children: React.JSX.Element;
}

const PageWrapper = memo(function PageWrapper({
	themeType,
	children,
}: PageWrapperProps): React.JSX.Element {
	const { showDashboard } = useContext(SubscriptionPlansApiContext);

	const handleBackClick = useMemo(
		() => () => {
			showDashboard();
		},
		[showDashboard]
	);

	return (
		<div
			className={`vscode-${themeType} w-full h-full bg-[var(--vscode-welcomePage-background)]`}
		>
			<div className="p-6 max-w-6xl mx-auto">
				{/* Header */}
				<div className="flex items-center mb-8">
					<button
						onClick={handleBackClick}
						className="flex items-center text-[var(--vscode-foreground)] hover:text-[var(--color-kiro-purple-primary)] mr-4"
					>
						<i
							className="codicon codicon-arrow-left"
							style={{ fontSize: "24px" }}
						></i>
					</button>
					<h1 className="text-lg font-medium text-[var(--vscode-foreground)]">
						Plan options
					</h1>
				</div>
				{children}
			</div>
		</div>
	);
});

export function SubscriptionPlansPage({
	themes,
	currentThemeId,
}: SubscriptionPlansPageProps): React.JSX.Element {
	const {
		subscriptionPlans,
		loading,
		error,
		handleUpgrade,
		clearError,
		disclaimers,
	} = useSubscriptionPlans();

	const themeType =
		themes.find((theme) => theme.id === currentThemeId)?.type || "dark";

	const plans = useMemo(
		() => transformSubscriptionPlansToUI(subscriptionPlans),
		[subscriptionPlans]
	);

	if (loading) {
		return (
			<PageWrapper themeType={themeType}>
				<LoadingSkeleton />
			</PageWrapper>
		);
	}

	return (
		<PageWrapper themeType={themeType}>
			<>
				<ErrorBanner
					error={error}
					hasNoPlans={subscriptionPlans.length === 0}
					onDismiss={clearError}
				/>

				{/* Plans Grid */}
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
					{plans.map((plan) => (
						<PlanCard key={plan.name} plan={plan} onUpgrade={handleUpgrade} />
					))}
				</div>

				{/* Information Section */}
				<div className="flex items-start gap-2 mt-4 text-sm text-[var(--vscode-descriptionForeground)]">
					<i className="codicon codicon-info mt-0.5 flex-shrink-0"></i>
					<p>{disclaimers.join(" ")}</p>
				</div>
			</>
		</PageWrapper>
	);
}
