import { useEffect, useState, RefObject } from "react";
import { ArrowDown } from "lucide-react";
import { cn } from "@/lib/utils";

interface ScrollToBottomButtonProps {
  scrollAreaRef: RefObject<HTMLDivElement>;
  threshold?: number;
}

export function ScrollToBottomButton({ scrollAreaRef, threshold = 300 }: ScrollToBottomButtonProps) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const root = scrollAreaRef.current;
    if (!root) return;
    const viewport = root.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement | null;
    if (!viewport) return;

    const onScroll = () => {
      const distance = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
      setVisible(distance > threshold);
    };
    onScroll();
    viewport.addEventListener("scroll", onScroll, { passive: true });
    return () => viewport.removeEventListener("scroll", onScroll);
  }, [scrollAreaRef, threshold]);

  const scrollToBottom = () => {
    const viewport = scrollAreaRef.current?.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement | null;
    if (viewport) viewport.scrollTo({ top: viewport.scrollHeight, behavior: "smooth" });
  };

  if (!visible) return null;

  return (
    <button
      onClick={scrollToBottom}
      aria-label="滚动到底部"
      className={cn(
        "absolute bottom-4 left-1/2 -translate-x-1/2 z-10",
        "h-9 w-9 rounded-full bg-background/90 backdrop-blur",
        "border border-border/60 shadow-md hover:shadow-lg",
        "flex items-center justify-center text-foreground",
        "hover:bg-surface transition-all duration-200 animate-fade-in"
      )}
    >
      <ArrowDown className="h-4 w-4" />
    </button>
  );
}
