// @flow
import React from 'react';
import { renderToString } from 'react-dom/server';
import { getPaletteColor } from '../../../mixins/branding';
import type { ThemeProps } from '../../../types';
import { Lock as LockIcon, ErrorIcon } from '../../icon';
import type { MaskedTextInputProps } from './masked-text-input.proptypes';

const hasError = ({ error }) =>
  error === true || typeof error === 'string' || typeof error === 'object';

export const getInputHeight = ({ large }: MaskedTextInputProps<string>) =>
  large ? '60px' : '40px';

export const getInputLeftPadding = ({
  large,
  iconType,
  iconPosition = 'left',
}: MaskedTextInputProps<string>) => {
  if (iconType && iconPosition === 'left') {
    return large ? '60px' : '40px';
  }

  return large ? '30px' : '20px';
};

export const getInputIconPosition = ({
  iconPosition = 'left',
  ...rest
}: MaskedTextInputProps<string>) => {
  let finalIconPosition = iconPosition;

  if (hasError(rest)) {
    finalIconPosition = 'right';
  }

  return `${finalIconPosition} center`;
};

export const getTextColor = (props: MaskedTextInputProps<string>) =>
  getPaletteColor(hasError(props) ? 'error-fg' : 'greyscale-black');

export const getPlaceholderColor = () => getPaletteColor('greyscale-medium');

const getIcon = (props: ThemeProps & MaskedTextInputProps<string>) => {
  if (hasError(props)) {
    return <ErrorIcon {...props} />;
  }

  switch (props.iconType) {
    case 'error':
      return <ErrorIcon {...props} />;
    case 'lock':
      return <LockIcon {...props} />;

    default:
      return null;
  }
};

export const getIconDataUri = (
  props: ThemeProps & MaskedTextInputProps<string>,
) => {
  if (!props.iconType && !hasError(props)) return undefined;

  const encodedIcon = encodeURIComponent(renderToString(getIcon(props)));
  return `url(data:image/svg+xml;utf8,${encodedIcon})`;
};
