import { Button, ButtonProps } from "@/components/ui/button";
import { useEditor } from "novel";
import { RedoIcon, UndoIcon } from "lucide-react";
import {
  inlineSelectorItems,
  selectionItems,
} from "../selector/selection-items";
import { cn } from "@/lib/utils";

export const MenuBar = ({
  onlyInline = false,
  className,
  buttonProps,
}: {
  onlyInline?: boolean;
  className?: string;
  buttonProps?: ButtonProps;
}) => {
  const { editor } = useEditor();

  if (!editor) {
    return null;
  }
  const items = onlyInline ? inlineSelectorItems : selectionItems;
  return (
    <div
      className={cn(
        "sticky top-0 z-50 flex justify-between gap-1 bg-background py-4",
        className,
      )}
    >
      <div className="flex flex-wrap gap-1">
        {items.map((item) => (
          <Button
            key={item.name}
            size={"icon"}
            variant={"outline"}
            onClick={() => item.command(editor)}
            disabled={item?.canRun ? item.canRun(editor) : false}
            {...buttonProps}
            className={cn(
              item.isActive(editor) && "border-foreground/75",
              buttonProps?.className,
            )}
          >
            <item.icon />
          </Button>
        ))}
      </div>
      <div className="flex gap-1">
        <Button
          variant={"outline"}
          size={"icon"}
          onClick={() => editor.chain().focus().undo().run()}
          disabled={!editor.can().chain().focus().undo().run()}
          {...buttonProps}
        >
          <UndoIcon className="size-4" />
        </Button>
        <Button
          variant={"outline"}
          size={"icon"}
          onClick={() => editor.chain().focus().redo().run()}
          disabled={!editor.can().chain().focus().redo().run()}
          {...buttonProps}
        >
          <RedoIcon className="size-4" />
        </Button>
      </div>
    </div>
  );
};
