import { useEffect } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { Button } from "@/components/ui/button";

type Props = {
  open: boolean;
  onClose: () => void;
  title?: React.ReactNode;
  /** Extra actions in the header, right of title */
  actions?: React.ReactNode;
  children: React.ReactNode;
  /** Width class, e.g. "max-w-[720px]" */
  width?: string;
};

/**
 * Generic right-side drawer panel with backdrop.
 * Self-manages escape key and body scroll lock.
 */
export default function RightDrawer({
  open,
  onClose,
  title,
  actions,
  children,
  width = "max-w-[720px]",
}: Props) {
  // Escape to close
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  // Lock body scroll
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  if (!open) return null;

  return createPortal(
    <div className="fixed inset-y-0 right-0 z-50 flex w-full justify-end">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-background/50 backdrop-blur-sm animate-in fade-in duration-200"
        onClick={onClose}
      />

      {/* Panel */}
      <div
        className={`relative flex h-full w-full flex-col border-l border-border/30 bg-card shadow-2xl animate-in slide-in-from-right duration-300 ${width}`}
      >
        {/* Header */}
        <div className="flex shrink-0 items-center gap-3 border-b border-border/40 px-5 py-3">
          <Button
            className="size-8 shrink-0 cursor-pointer rounded-lg"
            onClick={onClose}
            size="icon"
            variant="ghost"
          >
            <X className="size-4" />
          </Button>
          {typeof title === "string" ? (
            <span className="min-w-0 flex-1 truncate text-sm font-semibold">
              {title}
            </span>
          ) : (
            <div className="min-w-0 flex-1">{title}</div>
          )}
          {actions}
        </div>

        {/* Body */}
        <div className="min-h-0 flex-1 overflow-y-auto">
          {children}
        </div>
      </div>
    </div>,
    document.body,
  );
}
