import React from "react";
import classNames from "classnames";
import { TableAddon } from "../TableProps";
import { Tooltip, TooltipProps } from "../../tooltip";

/**
 * `rowtooltip` 插件用于支持为表格行生成 `tooltip`。
 */
export interface RowTooltipAddonOption<T = any> {
  /**
   * 为指定的行生成 `tooltip` 内容，返回空则不显示 `tooltip`
   */
  tooltip: (record: T) => React.ReactNode;
}

export function rowtooltip<T = any>(
  options: RowTooltipAddonOption<T>
): TableAddon<T> {
  return {
    getInfo: () => ({ name: "rowtooltip" }),
    onInjectRow: next => (...args) => {
      const result = next(...args);

      // 对于提供了 tooltip 的，用 tooltip 包裹
      const [record] = args;
      const tooltip = options.tooltip(record);
      if (tooltip) {
        result.row = (
          <TooltipWrapper key={result.row.key} tooltip={tooltip}>
            {result.row}
          </TooltipWrapper>
        );
      }

      return result;
    },
  };
}

function TooltipWrapper({
  children,
  tooltip,
  ...props
}: React.HTMLAttributes<HTMLTableRowElement> & {
  tooltip: TooltipProps["title"];
  children: React.ReactElement<React.HTMLAttributes<HTMLTableRowElement>>;
}) {
  return (
    <Tooltip title={tooltip}>
      {React.cloneElement(
        React.Children.only(children as React.ReactElement<any>),
        {
          ...props,
          // eslint-disable-next-line react/destructuring-assignment
          className: classNames(props.className, children.props.className),
        }
      )}
    </Tooltip>
  );
}
