"use client";

import {
	ResizableHandle,
	ResizablePanel,
	ResizablePanelGroup,
} from "@mdxui/primitives/resizable";
import { useCallback, useEffect, useRef, useState } from "react";
import { EditorPane } from "./editor/editor-pane";
import type { EditorHandle } from "./editor-context";
import { PreviewPane } from "./preview/preview-pane";

interface EditorSplitPaneProps {
	content: string;
	onChange: (content: string) => void;
	path: string;
	isDirty?: boolean;
	isSaving?: boolean;
	onSave?: () => void;
	onClose?: () => void;
}

export function EditorSplitPane({
	content,
	onChange,
	path,
	isDirty,
	isSaving,
	onSave,
	onClose,
}: EditorSplitPaneProps) {
	const [defaultLayout, setDefaultLayout] = useState<number[]>([50, 50]);
	const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const editorHandleRef = useRef<EditorHandle | null>(null);

	// Load saved layout from localStorage
	useEffect(() => {
		if (typeof window !== "undefined") {
			const saved = localStorage.getItem("editor-panel-layout");
			if (saved) {
				try {
					const parsed = JSON.parse(saved);
					if (Array.isArray(parsed) && parsed.length === 2) {
						setDefaultLayout(parsed);
					}
				} catch {
					// Ignore parse errors
				}
			}
		}
	}, []);

	// Cleanup timeout on unmount
	useEffect(() => {
		return () => {
			if (saveTimeoutRef.current) {
				clearTimeout(saveTimeoutRef.current);
			}
		};
	}, []);

	// Debounced localStorage save (500ms delay)
	const handleLayout = useCallback((sizes: number[]) => {
		if (saveTimeoutRef.current) {
			clearTimeout(saveTimeoutRef.current);
		}
		saveTimeoutRef.current = setTimeout(() => {
			localStorage.setItem("editor-panel-layout", JSON.stringify(sizes));
		}, 500);
	}, []);

	// Jump to line using editor handle ref
	const handleJumpToLine = useCallback((line: number) => {
		editorHandleRef.current?.jumpToLine(line);
	}, []);

	return (
		<ResizablePanelGroup
			direction="horizontal"
			onLayout={handleLayout}
			className="h-full"
		>
			<ResizablePanel
				defaultSize={defaultLayout[0]}
				minSize={25}
				className="bg-background"
			>
				<PreviewPane content={content} onJumpToLine={handleJumpToLine} />
			</ResizablePanel>

			<ResizableHandle
				withHandle
				className="w-2 bg-transparent transition-colors data-[resize-handle-active]:bg-border hover:bg-border/50"
			/>

			<ResizablePanel
				defaultSize={defaultLayout[1]}
				minSize={30}
				className="bg-background"
			>
				<EditorPane
					content={content}
					onChange={onChange}
					path={path}
					isDirty={isDirty}
					isSaving={isSaving}
					onSave={onSave}
					onClose={onClose}
					editorHandleRef={editorHandleRef}
				/>
			</ResizablePanel>
		</ResizablePanelGroup>
	);
}
