"use client";

import { Button } from "@mdxui/primitives/button";
import { cn } from "@mdxui/primitives/lib/utils";
import { RotateCcw, X } from "lucide-react";
import { memo } from "react";

interface RecoveryBannerProps {
	timestamp: number;
	onRestore: () => void;
	onDismiss: () => void;
}

function formatTimeSince(timestamp: number): string {
	const seconds = Math.floor((Date.now() - timestamp) / 1000);

	if (seconds < 60) return "just now";
	if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
	if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
	return `${Math.floor(seconds / 86400)}d ago`;
}

export const RecoveryBanner = memo(function RecoveryBanner({
	timestamp,
	onRestore,
	onDismiss,
}: RecoveryBannerProps) {
	return (
		<div
			className={cn(
				"flex items-center justify-between gap-3 px-4 py-2",
				"bg-linear-to-r from-muted/80 to-muted/40",
				"border-b border-border",
				"text-sm",
			)}
		>
			<span className="text-muted-foreground text-xs sm:text-sm">
				Unsaved changes from{" "}
				<span className="block sm:inline text-foreground font-medium">
					{formatTimeSince(timestamp)}
				</span>
			</span>
			<div className="flex items-center gap-1">
				<Button
					variant="ghost"
					size="sm"
					onClick={onRestore}
					className="h-7 gap-1.5 text-xs"
				>
					<RotateCcw className="size-3" />
					Restore
				</Button>
				<Button
					variant="ghost"
					size="icon"
					onClick={onDismiss}
					className="size-7"
					aria-label="Dismiss"
				>
					<X className="size-3.5" />
				</Button>
			</div>
		</div>
	);
});
