import React from 'react';
import { nanoid } from 'nanoid';
import { ScaleLinear } from 'd3-scale';
import { Undefinable } from 'tsdef';
import { fp as _ } from '../../common/utils/fp';
import { SBox } from '../../common/s-components/layout/s-box';
import { SH5 } from '../../common/s-components/typography/s-h5';
import { formatDate } from '../transducers';
import { theme } from '../../app/theme';

type TProps = {
  ticks: Undefinable<number>[];
  scale: ScaleLinear<number, number>;
  yOffset?: number;
  yOffsetText?: number;
  variant?: 'small' | 'large' | 'latency';
  color?: string;
  ticksVariant?: 'distributed' | 'edge';
  alignRight?: boolean;
};

export const XAxisLabels: React.FC<TProps> = props => {
  const {
    ticks,
    scale,
    yOffset,
    yOffsetText,
    variant,
    color,
    ticksVariant,
    alignRight,
  } = props;
  const lastIndex = _.length(ticks) - 1;
  const width = 66;
  const isSmall = variant === 'small';

  return (
    <SBox position="absolute" top={yOffset! + 8} width={1}>
      {ticks.map((tick, index) => {
        let shift;
        let textAlign;
        if (isSmall) {
          shift = index === lastIndex ? -width : index > 0 ? -width / 2 : 0;
          textAlign =
            index === lastIndex ? 'right' : index > 0 ? 'center' : 'left';
        } else {
          shift = index === lastIndex && !alignRight ? -width : -width / 2;
          textAlign = index === lastIndex && !alignRight ? 'right' : 'center';
        }

        if (
          ticksVariant !== 'distributed' &&
          index > 0 &&
          index < ticks.length - 1
        )
          return null;

        return (
          <SBox
            key={nanoid()}
            position="absolute"
            left={scale(tick!)! + shift}
            top={yOffsetText}
            width={width}
          >
            <SBox>
              <SH5 normal color={color} textAlign={textAlign} mr={-3}>
                {formatDate(tick!)}
              </SH5>
            </SBox>
          </SBox>
        );
      })}
    </SBox>
  );
};

XAxisLabels.defaultProps = {
  yOffset: 0,
  yOffsetText: 0,
  variant: 'small',
  color: theme.colors.periwinkleGray,
  ticksVariant: 'distributed',
};
