import type { PopoverProps } from '@os-design/core';
import { EditorState } from 'draft-js';
import React, { useCallback } from 'react';
import Toolbar from './Toolbar.js';
import ToolbarButton from './ToolbarButton.js';
import type { BlockToolbarItem } from './blocks/types.js';
import getCurrentBlock from './utils/getCurrentBlock.js';

interface BlockToolbarProps extends Omit<PopoverProps, 'onChange'> {
  items: BlockToolbarItem[];
  value: EditorState;
  onChange: (value: EditorState) => void;
  setReadOnly: (readOnly: boolean) => void;
}

const BlockToolbar: React.FC<BlockToolbarProps> = ({
  items,
  value,
  onChange,
  setReadOnly,
  ...rest
}) => {
  const clickHandler = useCallback<(item: BlockToolbarItem) => void>(
    ({ onClick }) => {
      const currentBlock = getCurrentBlock(value);
      if (currentBlock.getType() !== 'unstyled' || currentBlock.getLength() > 0)
        return;
      onClick({
        value,
        onChange,
        setReadOnly,
      });
    },
    [value, onChange, setReadOnly]
  );

  return (
    <Toolbar {...rest}>
      {items.map((item) => (
        <ToolbarButton key={item.type} onClick={() => clickHandler(item)}>
          {item.icon}
        </ToolbarButton>
      ))}
    </Toolbar>
  );
};

export default BlockToolbar;
