import { Resizable } from 'react-resizable';
import style from './index.less';
const ResizableTitle = (props) => {
  const { onResize, width, ...restProps } = props;
  const { className, ...rest } = restProps;
  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className={style['react-resizable-handle']}
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...rest} className={`${className} ${style['react-resizable']}`} />
    </Resizable>
  );
};

export const components = {
  header: {
    cell: ResizableTitle,
  },
};

export const handleResize =
  (index, columns, setColumns) =>
  (_, { size }) => {
    const newColumns = [...columns];
    newColumns[index] = {
      ...newColumns[index],
      width: size.width,
    };
    setColumns(newColumns);
  };
export const getMergeColumns = (columns, setColumns) => {
  const mergeColumns = columns.map((col, index) => ({
    ...col,
    onHeaderCell: (column) => ({
      width: column.width,
      onResize: handleResize(index, columns, (value) => setColumns(value)),
    }),
  }));
  return mergeColumns;
};
