import { GridCellProps } from "@progress/kendo-react-grid";
import { useState, MouseEvent } from "react";

interface ActionCellProps {
  handleClick: (
    cellProps: GridCellProps,
    event: MouseEvent<HTMLTableCellElement>
  ) => void;
  cellProps: GridCellProps;
}

const ActionCell = ({ handleClick, cellProps }: ActionCellProps) => {
  const [isSelecting, setIsSelecting] = useState(false);

  const handleMouseDown = () => setIsSelecting(false);

  const handleMouseUp = () => {
    const selection = window.getSelection();
    if (selection && selection.toString().length > 0) {
      setIsSelecting(true);
    }
  };

  const onClick = (e: MouseEvent<HTMLTableCellElement>) => {
    if (!isSelecting) {
      handleClick(cellProps, e);
    }
  };
  return (
    <td
      id={cellProps.id}
      className={cellProps.className}
      role="gridcell"
      aria-colindex={cellProps.ariaColumnIndex}
      style={{ ...cellProps.style, cursor: "pointer", userSelect: "text" }}
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      onClick={onClick}
    >
      {cellProps.dataItem[cellProps.field ?? ""]}
    </td>
  );
};

export default ActionCell;
