// @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, Checkmark } from '../../icon';
import type { FormInputProps } from './form-input.proptypes';

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

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

export const getInputBorder = ({ hideBorder }: FormInputProps<string>) =>
  hideBorder ? 'none' : `1px solid`;

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

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

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

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

  if (iconType === 'checkmark' && iconPosition === 'right') {
    return `right ${large ? '18px' : '10px'} center`;
  }

  return `${finalIconPosition} center`;
};

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

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

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

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

    default:
      return null;
  }
};

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

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