import React from 'react';
import { nanoid } from 'nanoid';
import { ScaleLinear } from 'd3-scale';
import { Undefinable } from 'tsdef';
import { SBox } from '../../common/s-components/layout/s-box';
import { SH5 } from '../../common/s-components/typography/s-h5';
import { formatStream } from '../../common/transducers';
import { Icon } from '../../common/components/icon';
import { TIconName } from '../../common/types';
import { fp as _ } from '../../common/utils/fp';

type TProps = {
  offsetLeft: number;
  offsetTop?: number;
  ticks: Undefinable<number>[];
  scale: ScaleLinear<number, number>;
  variant?: 'small' | 'big' | 'latency';
  axisExclusion?: boolean;
  icons?: string[];
  alignRight?: boolean;
};

export const YAxisLabels: React.FC<TProps> = props => {
  const {
    offsetLeft,
    ticks,
    scale,
    offsetTop,
    variant,
    axisExclusion,
    icons,
    alignRight,
  } = props;
  const alignRightOffset = alignRight ? 60 : 0;

  let iconLength: number;
  if (icons) {
    iconLength = _.length(icons);
  }

  return (
    <SBox position="relative">
      {ticks.map((tick, index) => {
        if (index === 0 && variant === 'small') {
          return null;
        }

        return (
          <SBox
            key={nanoid()}
            position="absolute"
            top={scale(tick!)! - offsetTop!}
            left={offsetLeft - alignRightOffset}
            width={alignRight ? alignRightOffset : 'auto'}
            alignItems={alignRight ? 'flex-end' : 'flex-start'}
          >
            {variant === 'latency' ? (
              <SBox
                style={{
                  transform: [{ translateX: -22 }, { translateY: 8 }],
                }}
              >
                <SH5 normal color="periwinkleGray">
                  <Icon
                    name={_.path([iconLength - index], icons) as TIconName}
                    size={22}
                  />
                </SH5>
              </SBox>
            ) : (
              <SBox>
                <SH5 normal color="periwinkleGray">
                  {formatStream(tick, { axisExclusion })}
                </SH5>
              </SBox>
            )}
          </SBox>
        );
      })}
    </SBox>
  );
};

YAxisLabels.defaultProps = {
  offsetTop: 0,
  variant: 'small',
  axisExclusion: false,
};
