import { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import CopyToClipboard from 'react-copy-to-clipboard';
import CustomPropTypes from "../../../utils/prop-types/index.js";
import getColor from "../../../utils/colors/getColor.js";
import getMarginClasses from "../../../utils/css/getMarginClasses.js";
import IfActive from "../../application/IfActive/index.js";
import useResponsiveValues from "../../../hooks/breakpoint/useResponsiveValues/index.js";
import cx from "../../../utils/css/cx.js";
import Icon from './Icon';
import tools from './tools';
import classes from './styles.module.scss';
const cls = cx.merge(classes);

/**
 * Renders standard POLITICO article share tools. You have to specify the
 * headline and the URL that you want the tools to share. You can also
 * specify custom colors either by setting a color scale to pull from
 * automatically (e.g., `warmgray`) or by specifying individual custom colors.
 */
const ShareTools = function ShareTools(props) {
  const {
    shareUrl,
    shareHeadline,
    colorScale,
    moreBg,
    iconFg,
    border,
    borderHover,
    margin,
    inverted
  } = props;
  const [pageUrl, setPageUrl] = useState();
  const [pageTitle, setPageTitle] = useState();
  const [isOpen, setIsOpen] = useState(false);
  const [isCopied, setIsCopied] = useState(false);
  const marginValue = useResponsiveValues(margin);
  const margins = getMarginClasses(marginValue, {
    defaultSide: 'y',
    sides: ['y', 't', 'b']
  });
  const resolveColor = (value, stop, invertedStop) => {
    if (value) return getColor(value);
    const s = inverted ? invertedStop : stop;
    return getColor(`${colorScale || 'gray'}-${s}`);
  };
  const resolveMoreBg = () => {
    if (moreBg) return getColor(moreBg);
    if (inverted) return 'black';
    return 'white';
  };
  useEffect(() => {
    if (!isOpen) return undefined;
    const close = () => setIsOpen(false);
    window.document.addEventListener('click', close);
    return () => window.document.removeEventListener('click', close);
  }, [isOpen]);
  useEffect(() => {
    const timer = setTimeout(() => setIsCopied(false), 2000);
    return () => clearTimeout(timer);
  }, [isCopied]);
  useEffect(() => {
    setPageUrl(window.location.href);
    setPageTitle(window.document.title);
  });
  const hrefOpts = {
    shareHeadline: shareHeadline || pageTitle,
    shareUrl: shareUrl || pageUrl
  };
  return <div className={cls('shareRow', margins)} style={{
    '--ShareTools-morebg': resolveMoreBg(moreBg, '10', '90'),
    '--ShareTools-iconfg': resolveColor(iconFg, '90', '20'),
    '--ShareTools-border': resolveColor(border, '20', '50'),
    '--ShareTools-border-hover': resolveColor(borderHover, '40', '30')
  }}>
      <CopyToClipboard text={hrefOpts.shareUrl} onCopy={() => setIsCopied(true)}>
        <button type="button" className={classes.button}>
          <Icon icon="link" />
        </button>
      </CopyToClipboard>

      {tools.exposed.map(tool => <a key={tool.name} className={classes.button} href={tool.getHref(hrefOpts)} target="_blank" rel="noreferrer">
          {tool.icon}
        </a>)}

      <button type="button" className={classes.button} onClick={e => {
      e.stopPropagation();
      setIsOpen(old => !old);
    }}>
        <Icon icon="more" />
      </button>

      <IfActive active={isOpen}>
        <div className={classes.more}>
          {tools.hidden.map(tool => <a key={tool.name} type="button" className={classes.button} href={tool.getHref(hrefOpts)} target="_blank" rel="noreferrer">
              {tool.icon}
            </a>)}
        </div>
      </IfActive>

      <IfActive active={isCopied}>
        <div className={classes.copied}>
          Link copied
        </div>
      </IfActive>
    </div>;
};
ShareTools.defaultProps = {
  shareUrl: undefined,
  shareHeadline: undefined,
  colorScale: undefined,
  moreBg: undefined,
  iconFg: undefined,
  border: undefined,
  borderHover: undefined,
  margin: undefined,
  inverted: false
};
ShareTools.propTypes = {
  /**
   * The URL that will be shared. This will fall back to the current window
   * URL if you don't specify one.
   */
  shareUrl: PropTypes.string,
  /**
   * The headline that will be shared. This will fall back to the `title` of
   * the page if you don't specify one, but note that the `title` is generally
   * the SEO headline, which is usually not the headline you want to share.
   */
  shareHeadline: PropTypes.string,
  /**
   * The name of a color scale to pull share tool colors from automatically.
   */
  colorScale: PropTypes.string,
  /**
   * A custom color for the background of the more pop-up.
   */
  moreBg: PropTypes.string,
  /**
   * A custom color for the icons.
   */
  iconFg: PropTypes.string,
  /**
   * A custom color for the borders around icons and pop-ups.
   */
  border: PropTypes.string,
  /**
   * A custom color for the borders around icons on hover.
   */
  borderHover: PropTypes.string,
  /**
   * The vertical margins. Margins can be specified as one spacing
   * value that gets used on both top and bottom, an explicit `y` value, or
   * completely separate `tb` values. The values correspond to levels of our
   * spacing scale (e.g., `"4"` corresponds to `$spacing-4`). Note that grids
   * do not support custom horizontal margins.
   */
  margin: CustomPropTypes.responsive(PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
    y: PropTypes.string
  }), PropTypes.shape({
    t: PropTypes.string,
    b: PropTypes.string
  })])),
  /**
   * Invert colors when using automatic colors from a color scale. For use on
   * dark backgrounds.
   */
  inverted: PropTypes.bool
};
export default ShareTools;