import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { modifierCSS } from '../../helpers/index';

const propTypes = {
  children: PropTypes.node.isRequired,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  className: PropTypes.string,
  status: PropTypes.oneOf(['awaiting', 'requested', 'queued', 'running', 'succeeded', 'stopping', 'stopped', 'failed', 'skipped', 'unknown']).isRequired,
  isTimeline: PropTypes.bool,
  position: PropTypes.shape({
    left: PropTypes.string,
    width: PropTypes.string,
  }),
  style: PropTypes.object,
};

const defaultProps = {
  tag: 'div',
  defaultClassName: 'sui-prj-instance-quickview',
  className: '',
  isTimeline: false,
  position: undefined,
  style: {},
};

export const InstanceQuickview = (props) => {
  const {
    children,
    tag: Tag,
    defaultClassName,
    className,
    status,
    isTimeline,
    position,
    style,
    ...attributes
  } = props;

  const renderChildren = () => {
    if (!isTimeline) {
      return children;
    }

    const Items = (React.Children.toArray(children) || [])
      .flatMap((item) => React.Children.toArray(item));

    const PastJobs = Items
      .filter(((item) => item.props.status !== 'awaiting'));

    const AwaitingJobs = Items
      .filter(((item) => item.props.status === 'awaiting'));

    return (
      <>
        {PastJobs}
        <div className="sui-prj-instance-quickview__awaitingItems">
          {AwaitingJobs}
        </div>
      </>
    );
  };

  const classes = classnames(
    defaultClassName,
    modifierCSS(status),
    isTimeline ? 'as--timeline' : '',
    className
  );

  const styles = { ...style };
  if (position) {
    styles.left = `${position.left}`;
    styles.width = `${position.width}`;
  }

  return (
    <Tag {...attributes} className={classes} style={styles}>
      {renderChildren()}
    </Tag>
  );
};

InstanceQuickview.propTypes = propTypes;
InstanceQuickview.defaultProps = defaultProps;
