import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { FileTextIcon } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props {
    children: React.ReactNode;
    content: string;
    className?: string;
}

function getSnippet(content: string, maxLen = 120): string {
    const plain = content
        .replace(/[#*_~`>\[\]()!]/g, "")
        .replace(/\n+/g, " ")
        .trim();
    return plain.length > maxLen ? plain.slice(0, maxLen) + "…" : plain;
}

const MemoHoverCard = ({ children, content, className }: Props) => {
    if (!content) return <>{children}</>;

    return (
        <HoverCardPrimitive.Root openDelay={300} closeDelay={100}>
            <HoverCardPrimitive.Trigger asChild>{children}</HoverCardPrimitive.Trigger>
            <HoverCardPrimitive.Portal>
                <HoverCardPrimitive.Content
                    side="right"
                    align="start"
                    sideOffset={8}
                    className={cn(
                        "z-50 w-72 rounded-xl border border-border bg-background/95 backdrop-blur-md p-4 shadow-lg",
                        "data-[state=open]:animate-in data-[state=closed]:animate-out",
                        "data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0",
                        "data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95",
                        "data-[side=right]:slide-in-from-left-2",
                        "data-[side=left]:slide-in-from-right-2",
                        "data-[side=bottom]:slide-in-from-top-2",
                        "data-[side=top]:slide-in-from-bottom-2",
                        className,
                    )}
                >
                    <div className="flex items-start gap-3">
                        <div className="mt-0.5 p-1.5 rounded-lg bg-amber-500/10">
                            <FileTextIcon className="w-4 h-4 text-amber-500" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-xs font-medium text-muted-foreground mb-1">Memo Preview</p>
                            <p className="text-sm text-foreground leading-relaxed">{getSnippet(content)}</p>
                        </div>
                    </div>
                    <HoverCardPrimitive.Arrow className="fill-border" />
                </HoverCardPrimitive.Content>
            </HoverCardPrimitive.Portal>
        </HoverCardPrimitive.Root>
    );
};

export default MemoHoverCard;
