import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { Tooltip } from '../tooltip/Tooltip';

// Useful for .fromNow() relative time method.
dayjs.extend(relativeTime);

const propTypes = {
  /**
   * The date can be a number, a string, a Date or a dayjs compatible format.
   * It will be parsed by dayjs.
   */
  date: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
    PropTypes.instanceOf(Date),
    PropTypes.instanceOf(dayjs),
  ]),

  /**
   * Set to true to show a Tooltip with the date.
   */
  shouldShowTooltip: PropTypes.bool,

  /**
   * The different properties available in the Tooltip component.
   */
  tooltipProps: PropTypes.object,
};

const defaultProps = {
  date: undefined,
  shouldShowTooltip: false,
  tooltipProps: undefined,
};

const ONE_MINUTE_IN_MILLI_SECONDS = 60000;

const getDelay = (date) => {
  const diffMilliSeconds = dayjs().diff(dayjs(date));

  // Less than 1 minute
  if (diffMilliSeconds < ONE_MINUTE_IN_MILLI_SECONDS) {
    // Update every 15 seconds
    return ONE_MINUTE_IN_MILLI_SECONDS / 4;
  }

  // Less than 5 minutes
  if (diffMilliSeconds < 5 * ONE_MINUTE_IN_MILLI_SECONDS) {
    // Update every 1 minutes
    return ONE_MINUTE_IN_MILLI_SECONDS * 1;
  }

  // Less thant 10 minutes
  if (diffMilliSeconds < 10 * ONE_MINUTE_IN_MILLI_SECONDS) {
    // Update each 2 minutes
    return ONE_MINUTE_IN_MILLI_SECONDS * 2;
  }

  // Update every 5 minutes
  return ONE_MINUTE_IN_MILLI_SECONDS * 5;
};

export const TimeFromNow = ({ date, shouldShowTooltip, tooltipProps }) => {
  const [updateView, setUpdateView] = useState(0);

  useEffect(() => {
    const timeout = setTimeout(
      () => {
        setUpdateView((x) => x + 1);
      },
      getDelay(date),
    );
    return () => clearTimeout(timeout);
  }, [updateView, date]);

  const fromNow = dayjs(date).fromNow();

  if (!shouldShowTooltip) {
    return fromNow;
  }

  return (
    <Tooltip label={dayjs(date).format('YYYY-MM-DD HH:mm:ss')} wrapperTag="span" {...tooltipProps}>
      {fromNow}
    </Tooltip>
  );
};

TimeFromNow.propTypes = propTypes;
TimeFromNow.defaultProps = defaultProps;
