import React from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';

import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

import styles from './CustomTooltip.module.scss';

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);

function CustomTooltip({ tooltipDateFormatter = null, ...props }) {
  const timezone = useSelector(getUserTimezoneSelector);
  return props.active && props.payload?.length ? (
    <div className={styles.Tooltip} style={{ backgroundColor: props.backgroundColor }}>
      {props.payload.map((item, index) => {
        if (item.color !== 'transparent') {
          return (
            <div key={`${index + 1}-${item.value}`}>
              {tooltipDateFormatter && item?.payload?.time && (
                <div>{tooltipDateFormatter(dayjs(item.payload.time).tz(timezone))}</div>
              )}
              {abbreviateNumber(item.value)}
            </div>
          );
        }

        return null;
      })}
    </div>
  ) : null;
}

CustomTooltip.propTypes = {
  active: PropTypes.bool.isRequired,
  payload: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  backgroundColor: PropTypes.string.isRequired,
  tooltipDateFormatter: PropTypes.func,
};

export default CustomTooltip;
