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 { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

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

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

function CustomTooltip({ formatter = null, ...props }) {
  const timezone = useSelector(getUserTimezoneSelector);

  return props.active && props.payload?.length ? (
    <div className={styles.Tooltip}>
      <p className={styles.Date}>
        {
          // eslint-disable-next-line react/prop-types
          props.tooltipDateFormatter(dayjs(props.payload[0].payload.time).tz(timezone))
        }
      </p>
      {props.payload.map((item, index) => {
        if (item.color !== 'transparent') {
          return (
            <div key={`${index + 1}-${item.value}`} className={styles.Row}>
              <span className={styles.Color} style={{ backgroundColor: item.color }} />
              <span className={styles.Value}>{formatter ? formatter(item.value) : item.value}</span>
            </div>
          );
        }

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

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

export default CustomTooltip;
