import React, { ReactElement } from 'react';

import { AffixWrapper } from './StyledInput';
import { Size } from './utils';
import Icon, { IconName } from '../Icon';
import { getOrElse, map, none, Option, some } from '../../fp/Option';
import { pipe } from '../../fp/function';
import { Either, match, left, right } from '../../fp/Either';

const Affix = ({
  affix,
  themeSize,
  themeMarginLeft = 'none',
}: {
  affix?: IconName | ReactElement;
  themeMarginLeft?: 'auto' | 'none';
  themeSize: Size;
}): ReactElement | null => {
  const renderWithWrapper = (children: string | ReactElement): ReactElement => (
    <AffixWrapper themeSize={themeSize} themeMarginLeft={themeMarginLeft}>
      {children}
    </AffixWrapper>
  );
  return pipe(
    affix,
    (
      value?: IconName | ReactElement
    ): Option<Either<IconName, ReactElement>> => {
      if (typeof value === 'string') {
        return some(left(value));
      }
      if (React.isValidElement(value)) {
        return some(right(value));
      }
      return none;
    },
    map(
      match(
        value => renderWithWrapper(<Icon icon={value} intent="subdued-text" />),
        renderWithWrapper
      )
    ),
    getOrElse(() => null)
  );
};

export default Affix;
