import React from 'react';
import PropTypes from 'prop-types';
import { AdjustOutlined, ArrowCircleDown, ArrowCircleUp, InfoOutlined } from '@mui/icons-material';

import { Grid, Tooltip, Typography } from '@/mui/components';

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

function Total({ prefix = '', postfix = '', needMultiply = false, change = null, tooltip = null, ...props }) {
  const value = props.value ?? null;
  const valueMultiplied = needMultiply ? value * 100 : value;
  const valueFormatted = valueMultiplied?.toLocaleString(undefined, {
    minimumFractionDigits: prefix?.length || postfix?.length ? 2 : 0,
    maximumFractionDigits: 2,
  });

  const roundedPercent = change ? Math.round(change * 100) : 0;
  const percentFormatted = roundedPercent > 0 ? `+${roundedPercent}%` : `${roundedPercent}%`;
  let IconPercent = AdjustOutlined;

  if (roundedPercent > 0) {
    IconPercent = ArrowCircleUp;
  }

  if (roundedPercent < 0) {
    IconPercent = ArrowCircleDown;
  }

  return (
    <Grid item xs="auto" className={styles.Total}>
      <div className={styles.Header}>
        <Typography variant="caption" color="text.secondary" fontWeight={400}>
          {props.header}
        </Typography>

        {tooltip?.length && (
          <Tooltip title={tooltip} placement="top">
            <div className={styles.InfoTooltip}>
              <InfoOutlined size="small" color="info" />
            </div>
          </Tooltip>
        )}
      </div>

      <Typography className={styles.Value} variant="subtitle1" color="text.primary" fontWeight={400}>
        {value !== null ? `${prefix ?? ''}${valueFormatted ?? ''}${postfix ?? ''}` : 'N/A'}
      </Typography>

      {!Number.isNaN(parseInt(change, 10)) && (
        <Typography variant="caption" color={roundedPercent < 0 ? 'error.main' : 'success.main'} fontWeight={400}>
          {percentFormatted}
          <IconPercent className={styles.PercentIcon} fontSize="small" />
        </Typography>
      )}
    </Grid>
  );
}

Total.propTypes = {
  header: PropTypes.string.isRequired,
  value: PropTypes.number.isRequired,
  change: PropTypes.number,
  prefix: PropTypes.string,
  postfix: PropTypes.string,
  needMultiply: PropTypes.bool,
  tooltip: PropTypes.string,
};

export default Total;
