import React from 'react';
import { Icon } from './icon';
import { theme } from '../../app/theme';
import { SPositionTrendsLabel } from '../s-components/s-position-trends-label';
import { fp as _ } from '../utils/fp';
import { SBox } from '../s-components/layout/s-box';
import { ZeroTrend } from './zero-trend';
import { getTrendValue } from '../transducers';
import { TTrend, TTrendFormatted, TCssRules, TPositionTrend } from '../types';
import { absString } from '../transducers/transducers.formatting';
import { SPositionTrendsLabelValue } from '../s-components/s-position-trends-label-value';

type TProps = {
  trend: TPositionTrend;
  isTransparent?: boolean;
  isReversed?: boolean;
  showZerroTrend?: boolean;
  showPercent?: boolean;
  downColor?: string;
  upColor?: string;
  zeroColor?: string;
} & TCssRules;

export const PositionTrendsLabel: React.FC<TProps> = props => {
  const {
    trend,
    isTransparent,
    isReversed,
    showZerroTrend,
    showPercent,
    downColor,
    upColor,
    zeroColor,
    ...rest
  } = props;

  const value = _.path('value', trend);
  const valueFormatted = _.path<any, any>('valueFormatted', trend);

  const isRankIncreased = isReversed
    ? Math.sign(value! as number) > 0
    : Math.sign(value! as number) < 0;
  const iconName = isRankIncreased ? 'arrow-up' : 'arrow-down';
  const color = !isTransparent
    ? 'white'
    : isRankIncreased
    ? upColor
    : downColor;
  const valueFormattedAbs =
    isRankIncreased && valueFormatted
      ? absString(valueFormatted)
      : valueFormatted;
  const trendValue = getTrendValue(
    value as TTrend,
    valueFormattedAbs as TTrendFormatted
  );

  if (showZerroTrend && value === 0) {
    return (
      <SBox {...rest}>
        <ZeroTrend zeroColor={zeroColor} showPercent={showPercent} />
      </SBox>
    );
  }
  if (_.isNil(value) || _.isEmpty(value)) {
    return null;
  }

  return (
    <SPositionTrendsLabel
      testID="trend"
      isRankIncreased={isRankIncreased}
      isTransparent={isTransparent}
      {...rest}
    >
      <Icon name={iconName} size={12} color={color} />
      <SPositionTrendsLabelValue color={color}>
        {trendValue}
        {showPercent ? '%' : null}
      </SPositionTrendsLabelValue>
    </SPositionTrendsLabel>
  );
};

PositionTrendsLabel.defaultProps = {
  isTransparent: false,
  isReversed: false,
  showZerroTrend: false,
  showPercent: false,
  downColor: theme.colors.sunsetOrange,
  upColor: theme.colors.emerald,
};
