// @flow
import React from 'react';
import { ThemeProvider } from 'styled-components';
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';
import type { FontSize } from '../../../../mixins/typography';

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

export const getInputVerticalPadding = ({
  large,
  fontSize,
}: MaskedTextInputProps<string>) => {
  if (fontSize === 'f5') {
    return '15px';
  }

  return large ? '10px' : '2px';
};

export const getInputFontSize = ({
  fontSize,
  large,
}: {
  fontSize?: FontSize,
  large?: boolean,
}) => {
  if (fontSize == null) {
    return large ? 'f3' : 'f1';
  }

  return fontSize;
};

export const getBackgroundColor = ({
  hideBorder,
  disabled,
}: MaskedTextInputProps<string>) =>
  disabled && !hideBorder ? getPaletteColor('background') : 'white';

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

export const getInputLeftPadding = ({
  large,
  iconType,
  iconPosition = 'left',
  hideBorder = false,
}: MaskedTextInputProps<string>) => {
  if (hideBorder) {
    return '0px';
  }
  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-dark');

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

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

    default:
      return null;
  }
};

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

  const themed = (
    <ThemeProvider theme={props.theme}>{getIcon(props)}</ThemeProvider>
  );

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