"use client";

import { Kbd } from "@mdxui/primitives/kbd";
import { cn } from "@mdxui/primitives/lib/utils";
import {
	Tooltip,
	TooltipContent,
	TooltipProvider,
	TooltipTrigger,
} from "@mdxui/primitives/tooltip";
import { GripVertical, Pencil } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import type { EditorTriggerProps } from "./types";

const STORAGE_KEY = "editor-trigger-position";
const DEFAULT_POSITION = 33; // percentage from top

export function EditorTrigger({ isOpen, onToggle }: EditorTriggerProps) {
	const [showOnboarding, setShowOnboarding] = useState(false);
	const [isPressed, setIsPressed] = useState(false);
	const [isDragging, setIsDragging] = useState(false);
	const [positionPercent, setPositionPercent] = useState(DEFAULT_POSITION);
	const triggerRef = useRef<HTMLButtonElement>(null);
	const dragStartY = useRef(0);
	const dragStartPercent = useRef(0);

	// Load saved position
	useEffect(() => {
		if (typeof window === "undefined") return;
		const saved = localStorage.getItem(STORAGE_KEY);
		if (saved) {
			const parsed = parseFloat(saved);
			if (!isNaN(parsed) && parsed >= 10 && parsed <= 90) {
				setPositionPercent(parsed);
			}
		}
	}, []);

	// Onboarding tooltip
	useEffect(() => {
		const onboarded = localStorage.getItem("editor-onboarded") === "true";
		if (!onboarded) {
			const timer = setTimeout(() => setShowOnboarding(true), 2000);
			return () => clearTimeout(timer);
		}
	}, []);

	const handleDismissOnboarding = () => {
		setShowOnboarding(false);
		localStorage.setItem("editor-onboarded", "true");
	};

	const handleClick = () => {
		// Don't trigger click if we were dragging
		if (isDragging) return;
		if (showOnboarding) {
			handleDismissOnboarding();
		}
		onToggle();
	};

	// Drag handling
	const handleDragStart = useCallback(
		(e: React.MouseEvent | React.TouchEvent) => {
			e.preventDefault();
			e.stopPropagation();
			setIsDragging(true);
			dragStartY.current = "touches" in e ? e.touches[0].clientY : e.clientY;
			dragStartPercent.current = positionPercent;
		},
		[positionPercent],
	);

	useEffect(() => {
		if (!isDragging) return;

		let rafId: number | null = null;

		const handleMove = (e: MouseEvent | TouchEvent) => {
			const clientY = "touches" in e ? e.touches[0].clientY : e.clientY;
			const deltaY = clientY - dragStartY.current;
			const deltaPercent = (deltaY / window.innerHeight) * 100;

			if (rafId) return;
			rafId = requestAnimationFrame(() => {
				const newPercent = Math.max(
					10,
					Math.min(90, dragStartPercent.current + deltaPercent),
				);
				setPositionPercent(newPercent);
				rafId = null;
			});
		};

		const handleEnd = () => {
			setIsDragging(false);
			// Save position
			localStorage.setItem(STORAGE_KEY, positionPercent.toString());
		};

		document.addEventListener("mousemove", handleMove, { passive: true });
		document.addEventListener("mouseup", handleEnd);
		document.addEventListener("touchmove", handleMove, { passive: true });
		document.addEventListener("touchend", handleEnd);

		document.body.style.cursor = "grabbing";
		document.body.style.userSelect = "none";

		return () => {
			document.removeEventListener("mousemove", handleMove);
			document.removeEventListener("mouseup", handleEnd);
			document.removeEventListener("touchmove", handleMove);
			document.removeEventListener("touchend", handleEnd);
			document.body.style.cursor = "";
			document.body.style.userSelect = "";
			if (rafId) cancelAnimationFrame(rafId);
		};
	}, [isDragging, positionPercent]);

	// Hide trigger when drawer is open (drawer has its own close button)
	if (isOpen) return null;

	return (
		<TooltipProvider>
			<Tooltip open={showOnboarding || undefined} delayDuration={400}>
				<TooltipTrigger asChild>
					<button
						type="button"
						ref={triggerRef}
						onClick={handleClick}
						onMouseDown={() => !isDragging && setIsPressed(true)}
						onMouseUp={() => setIsPressed(false)}
						onMouseLeave={() => setIsPressed(false)}
						aria-label="Edit page content"
						style={{ top: `${positionPercent}%` }}
						className={cn(
							// Position: right edge, vertical position from state
							"fixed right-0 z-9998 -translate-y-1/2",
							// Tab shape: rectangle with rounded left corners
							"flex flex-col items-center justify-center gap-1",
							"h-20 w-7 rounded-l-lg",
							// Styling
							"bg-card/95 backdrop-blur-xl",
							"border border-r-0 border-border",
							"shadow-lg",
							"cursor-pointer select-none",
							"transition-all duration-150",
							"hover:w-9 hover:bg-accent/50",
							isPressed && "w-8 bg-accent",
							isDragging && "w-9 bg-accent/50 cursor-grabbing",
						)}
					>
						{/* Drag handle - top */}
						{/** biome-ignore lint/a11y/noStaticElementInteractions: we need to add interactivity to the drag handle */}
						<div
							onMouseDown={handleDragStart}
							onTouchStart={handleDragStart}
							className={cn(
								"flex items-center justify-center",
								"cursor-grab active:cursor-grabbing",
								"text-muted-foreground/50 hover:text-muted-foreground",
								"transition-colors",
							)}
						>
							<GripVertical className="size-3" />
						</div>

						{/* Edit icon */}
						<Pencil className="size-3.5 text-foreground" />

						{/* Drag handle - bottom */}
						{/** biome-ignore lint/a11y/noStaticElementInteractions: we need to add interactivity to the drag handle */}
						<div
							onMouseDown={handleDragStart}
							onTouchStart={handleDragStart}
							className={cn(
								"flex items-center justify-center",
								"cursor-grab active:cursor-grabbing",
								"text-muted-foreground/50 hover:text-muted-foreground",
								"transition-colors",
							)}
						>
							<GripVertical className="size-3" />
						</div>
					</button>
				</TooltipTrigger>
				<TooltipContent
					side="left"
					sideOffset={8}
					className={cn(showOnboarding && "w-64 p-4")}
				>
					{showOnboarding ? (
						<div>
							<p className="font-medium font-mono">Edit Mode</p>
							<p className="mt-1.5 text-sm opacity-80 py-4 leading-relaxed">
								Edit this page directly. Click here or press <Kbd>⌘ I</Kbd> to
								open.
							</p>
							<button
								type="button"
								className="mt-3 w-full rounded-md bg-background px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-background/90 cursor-pointer"
								onClick={handleDismissOnboarding}
							>
								Got it
							</button>
						</div>
					) : (
						<p className="flex items-center gap-2">
							Edit page
							<Kbd>⌘I</Kbd>
						</p>
					)}
				</TooltipContent>
			</Tooltip>
		</TooltipProvider>
	);
}
