import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';

import { withSite } from './withSite';

/* Interface */
const propTypes = {
  /** An element type to render as (string or function). */
  as: PropTypes.oneOfType([
    PropTypes.func.isRequired,
    PropTypes.string.isRequired,
  ]).isRequired,

  /** Whether the text can be clicked to trigger update. */
  clickable: PropTypes.bool,

  /**
   * StoryShare `Site`.
   * @private
   */
  site: PropTypes.object.isRequired,

  /**
   * Update progress from StoryShare.
   * @private
   */
  updateProgress: PropTypes.number,

  /**
   * Update status from StoryShare.
   * @private
   */
  updateStatus: PropTypes.string,

  /**
   * Version from StoryShare.
   * @private
   */
  version: PropTypes.string,
};

/* Defaults */
const defaultProps = {
  as: 'div',
};

/**
 * Site version from SS configuration
 * Additional props will be passed through to the `<div>` or the component
 * specified by the `as` prop.
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const SiteVersion = ({
  as: Component,
  clickable,
  site,
  updateProgress,
  updateStatus,
  version,
  ...passThroughProps
}) => {
  if (!version) {
    return null;
  }

  const onClick = clickable ? () => site.autoupdate() : null;

  const statusMap = {
    [site.AUTOUPDATE_STATUS_PENDING_RESTART]: 'Update ready',
    [site.AUTOUPDATE_STATUS_ERROR]: 'Update failed',
    [site.AUTOUPDATE_STATUS_UPDATING]:
      `Updating: ${Math.round(updateProgress)}%`,
  };

  const status = statusMap[updateStatus] || `Version ${version}`;

  return (
    <Component onClick={ onClick } { ...passThroughProps }>
      { status }
    </Component>
  );
};

SiteVersion.propTypes = propTypes;
SiteVersion.defaultProps = defaultProps;

export const mapStateToProps = (_, { site }) => ({
  updateProgress: site.getUpdateProgress(),
  updateStatus: site.getUpdateStatus(),
  version: site.getVersion(),
});

// n.b. ordering: mapStateToProps needs site
export default withSite(connect(mapStateToProps)(SiteVersion));
