import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Tooltip } from '../../core/atoms/tooltip/Tooltip';
import { modifierCSS } from '../../helpers';

const STATUSES = [
  'awaiting', 'requested', 'queued', 'running', 'succeeded',
  'failed', 'skipped', 'created', 'up', 'stopping', 'stopped', 'down',
  'unknown', 'out_of_memory',
];

const propTypes = {
  /**
   * The Status content
   */
  children: PropTypes.node,

  /**
  * The component used for the root node.
  * Either a string to use a DOM element or a component.
  */
  tag: PropTypes.elementType,

  /**
   * The component default class.
   */
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),

  /**
   * The className property allows you to add more classes to the component.
   */
  className: PropTypes.string,

  /**
   * The Status name as defined by Saagie.
   */
  name: PropTypes.oneOf([
    ...STATUSES,
    ...STATUSES.map((status) => status.toUpperCase()),
  ]).isRequired,

  /**
   * The Status position for the component to add the correct spacing.
   */
  position: PropTypes.oneOf(['', 'start', 'between', 'end']),

  /**
   * The Status size.
   */
  size: PropTypes.oneOf(['', 'xs', 'sm', 'lg', 'xl']),

  /**
   * The Status information. Will add context in a Tooltip.
   */
  info: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),

  /**
   * The automatic display of the information on page or element events.
   */
  autoDisplayInfo: PropTypes.bool,

  /**
   * Object of props passed to the Tooltip component
   */
  tooltipProps: PropTypes.object,
};

const defaultProps = {
  children: '',
  tag: 'span',
  defaultClassName: 'sui-prj-status',
  className: '',
  position: '',
  size: '',
  info: '',
  autoDisplayInfo: false,
  tooltipProps: {},
};

export const Status = React.forwardRef(({
  children,
  tag: Tag,
  defaultClassName,
  className,
  name,
  position,
  size,
  info,
  autoDisplayInfo,
  tooltipProps,
  ...attributes
}, ref) => {
  const classes = classnames(
    defaultClassName,
    modifierCSS(name.toLowerCase()),
    modifierCSS(position),
    modifierCSS(size),
    className
  );

  return (
    <>
      {info ? (
        <Tooltip
          defaultPlacement="top"
          label={info}
          autoDisplay={autoDisplayInfo}
          {...tooltipProps}
        >
          <Tag {...attributes} className={classes} ref={ref}>
            {!children ? name.replaceAll('_', ' ') : children}
            {info && (
              <span className="sui-prj-status__dot" />
            )}
          </Tag>
        </Tooltip>
      ) : (
        <Tag {...attributes} className={classes} ref={ref}>
          {!children ? name.replaceAll('_', ' ') : children}
        </Tag>
      )}
    </>
  );
});

Status.propTypes = propTypes;
Status.defaultProps = defaultProps;
