"use client";

import { Button } from "@mdxui/primitives/button";
import { ArrowLeft, Moon, Sun } from "lucide-react";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import { useScroll } from "../lib/use-scroll";
import { cx } from "../lib/utils";
import { useOnboardingOptional } from "./onboarding-context";

// =============================================================================
// WIZARD-AWARE PROGRESS
// =============================================================================

interface WizardProgressProps {
	className?: string;
}

/**
 * Progress indicator that automatically derives steps from OnboardingWizard context
 */
export function WizardProgress({ className }: WizardProgressProps) {
	const onboarding = useOnboardingOptional();

	if (!onboarding) {
		return null;
	}

	const { steps, currentStep } = onboarding;

	return (
		// biome-ignore lint/a11y/useAriaPropsSupportedByRole: we are not using aria-label here <explanation>
		<div aria-label="Onboarding progress" className={className}>
			<ol className="mx-auto flex w-24 flex-nowrap gap-1 md:w-fit">
				{steps.map((step, index) => (
					<li
						key={step.path}
						className={cx(
							"h-1 w-12 rounded-full",
							index <= currentStep ? "bg-primary" : "bg-muted",
						)}
					>
						<span className="sr-only">
							{step.name}{" "}
							{index < currentStep
								? "completed"
								: index === currentStep
									? "current"
									: ""}
						</span>
					</li>
				))}
			</ol>
		</div>
	);
}

// =============================================================================
// THEME TOGGLE
// =============================================================================

interface WizardThemeToggleProps {
	theme?: string;
	setTheme?: (theme: string) => void;
}

/**
 * Theme toggle button - can be used with next-themes or custom theme state
 */
export function WizardThemeToggle({ theme, setTheme }: WizardThemeToggleProps) {
	if (!setTheme) {
		return null;
	}

	return (
		<Button
			variant="outline"
			size="icon"
			onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
		>
			<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
			<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
			<span className="sr-only">Toggle theme</span>
		</Button>
	);
}

// =============================================================================
// WIZARD HEADER
// =============================================================================

interface WizardHeaderProps {
	/** Back button href (external link, outside wizard) */
	backHref?: string;
	/** Back button text */
	backText?: string;
	/** Whether the header is collapsed (scrolled) */
	collapsed?: boolean;
	/** Theme for toggle (optional) */
	theme?: string;
	/** Theme setter (optional) */
	setTheme?: (theme: string) => void;
	/** Custom right-side content */
	rightContent?: ReactNode;
	/** Custom back button handler (overrides backHref link) */
	onBack?: () => void;
}

/**
 * Wizard-aware header with progress indicator
 * Uses react-router internally and derives progress from wizard context
 */
export function WizardHeader({
	backHref = "/",
	backText = "Home",
	collapsed = false,
	theme,
	setTheme,
	rightContent,
	onBack,
}: WizardHeaderProps) {
	return (
		<header
			className={cx(
				"fixed inset-x-0 top-0 isolate z-50 flex items-center justify-between border-b border-border bg-background px-4 transition-all md:grid md:grid-cols-[200px_auto_200px] md:px-6",
				collapsed ? "h-12" : "h-20",
			)}
		>
			<div className="flex flex-nowrap items-center gap-2">
				{onBack ? (
					<Button variant="ghost" size="sm" onClick={onBack}>
						<ArrowLeft className="h-4 w-4" />
						<span className="hidden sm:inline">{backText}</span>
					</Button>
				) : (
					<Button variant="ghost" size="sm" asChild>
						<Link to={backHref}>
							<ArrowLeft className="h-4 w-4" />
							<span className="hidden sm:inline">{backText}</span>
						</Link>
					</Button>
				)}
			</div>
			<div className="hidden flex-nowrap items-center gap-0.5 md:flex justify-center">
				<WizardProgress />
			</div>
			<div className="flex items-center justify-end gap-2">
				{rightContent ?? (
					<WizardThemeToggle theme={theme} setTheme={setTheme} />
				)}
			</div>
		</header>
	);
}

// =============================================================================
// WIZARD LAYOUT
// =============================================================================

interface WizardLayoutProps {
	children: ReactNode;
	/** Back button href (external, outside wizard) */
	backHref?: string;
	/** Back button text */
	backText?: string;
	/** Custom header component (replaces default) */
	header?: ReactNode;
	/** Whether to show the default header */
	showHeader?: boolean;
	/** Theme for toggle (optional) */
	theme?: string;
	/** Theme setter (optional) */
	setTheme?: (theme: string) => void;
	/** Custom back button handler */
	onBack?: () => void;
	/** Custom right-side header content */
	headerRightContent?: ReactNode;
}

/**
 * Layout wrapper that integrates with OnboardingWizard context
 * Automatically shows progress based on wizard steps
 *
 * @example
 * ```tsx
 * <OnboardingWizard
 *   basePath="/onboarding"
 *   steps={steps}
 *   layout={({ children }) => (
 *     <WizardLayout backHref="/" backText="Exit">
 *       {children}
 *     </WizardLayout>
 *   )}
 * />
 * ```
 */
export function WizardLayout({
	children,
	backHref = "/",
	backText = "Home",
	header,
	showHeader = true,
	theme,
	setTheme,
	onBack,
	headerRightContent,
}: WizardLayoutProps) {
	const scrolled = useScroll(15);

	return (
		<>
			{showHeader &&
				(header ?? (
					<WizardHeader
						collapsed={scrolled}
						backHref={backHref}
						backText={backText}
						theme={theme}
						setTheme={setTheme}
						onBack={onBack}
						rightContent={headerRightContent}
					/>
				))}
			<main id="main-content" className="mx-auto mb-20 mt-28 max-w-lg px-4">
				{children}
			</main>
		</>
	);
}
