/**
 * Locked Node Overlay
 *
 * Full-screen overlay for viewing a locked node as a "book" with pages.
 * Uses render props for app-specific content rendering.
 */

import React, { useEffect, type ReactNode, type ComponentType } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import {
	lockedNodeIdAtom,
	lockedNodeDataAtom,
	lockedNodePageIndexAtom,
	lockedNodePageCountAtom,
	unlockNodeAtom,
} from '../core/locked-node-store';
import type { UINodeState } from '../core/types';

// =============================================================================
// Types
// =============================================================================

export type LockedNodePage = {
	/** Unique key for the page */
	key: string;
	/** Display label for the page */
	label: string;
};

export type LockedNodeOverlayRenderContext = {
	/** The locked node ID */
	nodeId: string;
	/** The locked node data (from graph) */
	nodeData: UINodeState;
	/** Current page key */
	currentPage: string;
	/** Current page index */
	pageIndex: number;
	/** Total number of pages */
	totalPages: number;
	/** Function to close the overlay */
	close: () => void;
	/** Function to go to next page */
	nextPage: () => void;
	/** Function to go to previous page */
	prevPage: () => void;
	/** Function to go to a specific page by index */
	goToPage: (index: number) => void;
};

export type LockedNodeOverlayProps = {
	/** Page configuration */
	pages: LockedNodePage[];
	/** Render the page content */
	renderContent: (ctx: LockedNodeOverlayRenderContext) => ReactNode;
	/** Optional: Render a close button (default provided) */
	renderCloseButton?: (ctx: LockedNodeOverlayRenderContext) => ReactNode;
	/** Optional: Render the footer/navigation (default provided) */
	renderFooter?: (ctx: LockedNodeOverlayRenderContext) => ReactNode;
	/** Optional: Custom wrapper component for the overlay */
	WrapperComponent?: ComponentType<{ children: ReactNode }>;
	/** Optional: CSS class for the overlay container */
	className?: string;
	/** Optional: Inline styles for the overlay container */
	style?: React.CSSProperties;
};

// =============================================================================
// Default Components
// =============================================================================

const DefaultCloseButton: React.FC<{ onClick: () => void }> = ({ onClick }) => (
	<button
		onClick={onClick}
		className="absolute top-4 right-4 z-10 p-2 rounded hover:bg-white/10 transition-colors"
		style={{ color: 'var(--hud-text, #fff)', opacity: 0.6 }}
		aria-label="Close"
	>
		<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
			<line x1="18" y1="6" x2="6" y2="18" />
			<line x1="6" y1="6" x2="18" y2="18" />
		</svg>
	</button>
);

const DefaultFooter: React.FC<{
	pages: LockedNodePage[];
	currentIndex: number;
	onPageSelect: (index: number) => void;
}> = ({ pages, currentIndex, onPageSelect }) => (
	<footer
		className="flex items-center justify-center gap-8 py-4 border-t"
		style={{
			backgroundColor: 'var(--hud-header-bg, rgba(20, 20, 30, 0.9))',
			borderColor: 'var(--hud-border, rgba(255, 255, 255, 0.1))',
		}}
	>
		{/* Page dots indicator */}
		<div className="flex items-center gap-2">
			{pages.map((page, idx) => (
				<button
					key={page.key}
					onClick={() => onPageSelect(idx)}
					className="w-2.5 h-2.5 rounded-full transition-all hover:scale-110"
					style={{
						backgroundColor:
							idx === currentIndex
								? 'var(--hud-accent, #3b82f6)'
								: 'var(--hud-border, rgba(255, 255, 255, 0.3))',
						transform: idx === currentIndex ? 'scale(1.3)' : 'scale(1)',
					}}
					title={page.label}
				/>
			))}
		</div>

		{/* Keyboard hints */}
		<div className="flex items-center gap-4 text-xs" style={{ color: 'var(--hud-text, #fff)', opacity: 0.5 }}>
			<span>← → Navigate</span>
			<span>ESC Exit</span>
		</div>
	</footer>
);

const DefaultWrapper: React.FC<{ children: ReactNode }> = ({ children }) => <>{children}</>;

// =============================================================================
// Main Component
// =============================================================================

export function LockedNodeOverlay({
	pages,
	renderContent,
	renderCloseButton,
	renderFooter,
	WrapperComponent = DefaultWrapper,
	className = '',
	style,
}: LockedNodeOverlayProps) {
	const lockedNodeId = useAtomValue(lockedNodeIdAtom);
	const nodeData = useAtomValue(lockedNodeDataAtom);
	const pageIndex = useAtomValue(lockedNodePageIndexAtom);
	const setPageCount = useSetAtom(lockedNodePageCountAtom);
	const unlock = useSetAtom(unlockNodeAtom);

	// Initialize page count
	useEffect(() => {
		setPageCount(pages.length);
	}, [pages.length, setPageCount]);

	// Page navigation
	const goToPage = (index: number) => {
		if (index >= 0 && index < pages.length) {
			// We need to get the setter - using jotai directly
			// This is a simplified approach; in practice, the app might want to use atoms
		}
	};

	// For navigation, we'll use the atoms from locked-node-store
	// But we need access to the set functions
	const pageIndexSetter = useSetAtom(lockedNodePageIndexAtom);

	const nextPage = () => {
		pageIndexSetter((current) => (current + 1) % pages.length);
	};

	const prevPage = () => {
		pageIndexSetter((current) => (current - 1 + pages.length) % pages.length);
	};

	const handleGoToPage = (index: number) => {
		if (index >= 0 && index < pages.length) {
			pageIndexSetter(index);
		}
	};

	// Keyboard navigation
	useEffect(() => {
		if (!lockedNodeId) return;

		const handleKeyDown = (e: KeyboardEvent) => {
			// Ignore if typing in an input
			const target = e.target as HTMLElement;
			if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
				return;
			}

			switch (e.key) {
				case 'Escape':
					e.preventDefault();
					unlock();
					break;
				case 'ArrowRight':
				case 'ArrowDown':
					e.preventDefault();
					nextPage();
					break;
				case 'ArrowLeft':
				case 'ArrowUp':
					e.preventDefault();
					prevPage();
					break;
			}
		};

		window.addEventListener('keydown', handleKeyDown);
		return () => window.removeEventListener('keydown', handleKeyDown);
	}, [lockedNodeId, unlock, nextPage, prevPage]);

	// Don't render if no node is locked
	if (!lockedNodeId || !nodeData) return null;

	const currentPage = pages[pageIndex]?.key || pages[0]?.key;
	const totalPages = pages.length;

	const ctx: LockedNodeOverlayRenderContext = {
		nodeId: lockedNodeId,
		nodeData,
		currentPage,
		pageIndex,
		totalPages,
		close: unlock,
		nextPage,
		prevPage,
		goToPage: handleGoToPage,
	};

	return (
		<WrapperComponent>
			<div
				className={`fixed inset-0 z-[9999] flex flex-col ${className}`}
				style={{
					backgroundColor: '#0f0f14',
					isolation: 'isolate',
					...style,
				}}
			>
				{/* Content area */}
				<div className="flex-1 overflow-hidden relative">
					{/* Close button */}
					{renderCloseButton ? (
						renderCloseButton(ctx)
					) : (
						<DefaultCloseButton onClick={unlock} />
					)}

					{/* Page content */}
					{renderContent(ctx)}
				</div>

				{/* Footer/navigation */}
				{renderFooter ? (
					renderFooter(ctx)
				) : (
					<DefaultFooter pages={pages} currentIndex={pageIndex} onPageSelect={handleGoToPage} />
				)}
			</div>
		</WrapperComponent>
	);
}
