"use client";

import { cn } from "@mdxui/primitives/lib/utils";
import {
	Tabs,
	TabsContent,
	TabsList,
	TabsTrigger,
} from "@mdxui/primitives/tabs";
import { useCallback, useRef, useState } from "react";
import { EditorPane } from "../editor/editor-pane";
import type { EditorHandle } from "../editor-context";
import { PreviewPane } from "../preview/preview-pane";

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

export function MobileEditorTabs({
	content,
	onChange,
	path,
	isDirty,
	isSaving,
	onSave,
	onClose,
}: MobileEditorTabsProps) {
	const [activeTab, setActiveTab] = useState<string>("editor");
	const editorHandleRef = useRef<EditorHandle | null>(null);

	// Jump to line using editor handle ref
	const handleJumpToLine = useCallback((line: number) => {
		// Switch to editor tab first
		setActiveTab("editor");
		// Small delay to ensure tab switch completes, then jump
		requestAnimationFrame(() => {
			editorHandleRef.current?.jumpToLine(line);
		});
	}, []);

	return (
		<Tabs
			value={activeTab}
			onValueChange={setActiveTab}
			className="flex h-full flex-col"
		>
			<TabsList className="grid w-full grid-cols-2 rounded-none border-b border-border bg-card h-11">
				<TabsTrigger
					value="preview"
					className="rounded-none data-[state=active]:shadow-none"
				>
					Preview
				</TabsTrigger>
				<TabsTrigger
					value="editor"
					className="rounded-none data-[state=active]:shadow-none"
				>
					<span className="flex items-center gap-2">
						Editor
						{isDirty && (
							<span className={cn("size-2 rounded-full bg-chart-4")} />
						)}
					</span>
				</TabsTrigger>
			</TabsList>

			<TabsContent
				value="preview"
				className="flex-1 mt-0 data-[state=inactive]:hidden"
			>
				<PreviewPane content={content} onJumpToLine={handleJumpToLine} />
			</TabsContent>

			<TabsContent
				value="editor"
				className="flex-1 mt-0 data-[state=inactive]:hidden"
			>
				<EditorPane
					content={content}
					onChange={onChange}
					path={path}
					isDirty={isDirty}
					isSaving={isSaving}
					onSave={onSave}
					onClose={onClose}
					editorHandleRef={editorHandleRef}
				/>
			</TabsContent>
		</Tabs>
	);
}
