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);

  if (!props.active || !props.payload?.length) {
    return null;
  }

  const info = props.payload?.length === 1 ? props.payload?.[0] : props.payload?.[1]; // 0 is focus line
  const name = info?.name;
  const time = dayjs(info?.payload?.time).tz(timezone);
  const value = info?.payload?.value;
  const valueInFocus = info?.payload?.valueInFocus;

  return props.active && props.payload?.length ? (
    <div className={styles.Tooltip}>
      <p className={styles.TooltipText}>{name}</p>
      <p className={styles.TooltipDate}>{time.format('MMM DD, YYYY')}</p>
      <p className={styles.TooltipText}>{time.format('HH:mm')}</p>

      <p className={styles.TooltipText}>{`${props.title}: ${formatter ? formatter(value) : value}`}</p>

      <p className={styles.TooltipText}>{`In focus: ${formatter ? formatter(valueInFocus) : valueInFocus}`}</p>
    </div>
  ) : null;
}

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

export default CustomTooltip;
