/* eslint-disable no-bitwise */
import React, { useState } from 'react';
import PropTypes from 'prop-types';

import dispatch from '@core/utils/nativeDispatch';

import Flex from '@ui/components/Flex';
import Box from '@ui/components/Box';
import Button from '@ui/components/Button';
import Dropdown from '@ui/components/Dropdown';

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

const MetricsDateRange = props => {
  const menu = React.createRef();
  const paywalled = props.paywalled;
  const [timeAgo, setTimeAgo] = useState(paywalled ? 1 : props.timeAgo);
  const labels = {
    1: 'day',
    7: 'week',
    30: 'month',
  };
  const paywallClassMod = val => {
    if (paywalled && val !== '1') return '--paywall';
    return '';
  };
  const handleClick = function (event, value) {
    let displayValue = value;
    if (paywalled && value !== '1') displayValue = '1';
    else menu.current.toggle(false);
    // running setTimeAgo here instead of in nativeDispatch because the value
    // we set in this component is different than the one we dispatch to the
    // angular directive.
    setTimeAgo(displayValue);
    return dispatch(event, null, value);
  };
  return (
    <Flex align="center" className={classes.MetricsDateRange} justify="start">
      <span>Viewing metrics for the last:</span>
      <Dropdown ref={menu} align="start" justify="center">
        <Button bem={{ blue_ghost: true }} className="MetricsDateRange">
          <i className="fa fa-calendar fa-calendar-alt" />
          {'  '}
          {labels[timeAgo]} 
          <i className="fa fas fa-chevron-down fa-xs" style={{ fontSize: '.8em' }} />
        </Button>
        <Box bem={[['pop']]}>
          <div className="Flex Flex_col" style={{ margin: 0 }}>
            {Object.keys(labels).map(i => (
              <span
                key={`choose-daterange-${i}`}
                className={classes[`MetricsDateRange-quickSet${paywallClassMod(i)}`]}
                onClick={e => handleClick(e, i)}
                onKeyDown={e => e.key === 'Enter' && e.preventDefault() | handleClick(e, i)}
                role="button"
                tabIndex={0}
              >
                last {labels[i]}
              </span>
            ))}
          </div>
        </Box>
      </Dropdown>
    </Flex>
  );
};

MetricsDateRange.propTypes = {
  paywalled: PropTypes.bool,
  timeAgo: PropTypes.oneOf([1, 7, 30]),
};

MetricsDateRange.defaultProps = {
  paywalled: false,
  timeAgo: 1,
};

export default MetricsDateRange;
