import _ from "lodash";
import cn from "classnames";
import React, { forwardRef, useCallback } from "react";
import PropTypes from "prop-types";
import { getPressedKey, KEYS } from "../utils/keyboard";
import { Icon } from "../";
import exclamationTriangleIcon from "!!svg-sprite-loader!@cloudbees/honeyui-icons/solid/exclamation-triangle.svg";

interface IDialogTab {
  ["data-testid"]?: string;
  active?: boolean;
  className?: string;
  disabled?: boolean;
  invalid?: boolean;
  onClick: () => void;
}

const Tabs: React.FC<IDialogTab> = forwardRef((props, ref: React.Ref<HTMLLIElement>) => {
  const { children, className, disabled, active, invalid, onClick } = props;

  const onKeyPress = useCallback(
    (e: React.KeyboardEvent) => {
      if (!onClick) {
        return;
      }
      const key = getPressedKey(e);
      if (key === KEYS.Enter || key === KEYS.Space) {
        onClick();
      }
    },
    [onClick]
  );
  const dataTestId = props["data-testid"] || "dialog-header-tab-item";

  return (
    <li ref={ref} key={dataTestId} className="nav-item">
      <span
        data-testid={`${dataTestId}-link`}
        role="tab"
        tabIndex={0}
        className={cn("nav-link", "d-flex", "align-items-center", className, {
          "cursor-pointer": !disabled,
          active,
          disabled
        })}
        onKeyPress={e => !disabled && onKeyPress(e)}
        onClick={() => !disabled && onClick()}
      >
        {invalid ? (
          <Icon
            id={exclamationTriangleIcon.id}
            viewBox={exclamationTriangleIcon.viewBox}
            size="sm"
            className="mr-1"
            color="danger"
          />
        ) : null}
        {children}
      </span>
    </li>
  );
});

Tabs.displayName = "DialogHeaderTab";

Tabs.propTypes = {
  active: PropTypes.bool,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  invalid: PropTypes.bool,
  onClick: PropTypes.func.isRequired
};

export default Tabs;
