/* eslint-disable react/prop-types */
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 { CALENDAR_FILTER_VALUE } from '../../constants';

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

import { Typography } from '@/mui/components';

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

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

function CustomTooltip(props) {
  const timezone = useSelector(getUserTimezoneSelector);

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

  const calendarConfig = props.calendar === CALENDAR_FILTER_VALUE.custom ? props.calendarCustom : props.calendar;

  const params =
    props.activeCardFilter.id === 'PlatformFees'
      ? props.payload
      : props.payload.filter((item) => item.dataKey !== 'platformFee');
  const fees = props.payload.filter((item) => item.dataKey === 'platformFee');

  return props.active && props.payload?.length ? (
    <div className={styles.Tooltip}>
      <Typography variant="caption" color="text.primary" component="div" fontWeight={500}>
        {props.activeCardFilter.title}
      </Typography>

      {params.map((item) => {
        const { name, time } = item.payload;
        const value = item.payload[props.activeCardFilter.key];
        return (
          <Typography key={name} variant="captionSmall" color="text.primary" component="div">
            {`${calendarConfig.chartTooltipFormatter(dayjs(time).tz(timezone))}:
                ${props.activeCardFilter?.prefix ?? ''}${(
                  Math.round((props.activeCardFilter?.postfix ? value * 100 : value) * 100) / 100
                ).toLocaleString()}${props.activeCardFilter?.postfix ?? ''}`}
          </Typography>
        );
      })}

      {props.showFees && fees?.length && (
        <>
          <Typography variant="caption" color="text.primary" component="div" fontWeight={500} className={styles.Fees}>
            Platform fees
          </Typography>
          {fees.map((item) => {
            const { name, time } = item.payload;

            return (
              <Typography key={name} variant="captionSmall" color="text.primary" component="div">
                {`${calendarConfig.chartTooltipFormatter(dayjs(time).tz(timezone))}:
                    $${item.payload.platformFee?.toFixed(2)}`}
              </Typography>
            );
          })}
        </>
      )}
    </div>
  ) : null;
}

CustomTooltip.propTypes = {
  active: PropTypes.bool.isRequired,
  activeCardFilter: PropTypes.shape({}).isRequired,
  payload: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  calendar: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({})]).isRequired,
  calendarCustom: PropTypes.shape({}).isRequired,
  showFees: PropTypes.bool.isRequired,
};

export default CustomTooltip;
