import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components';
import roundedButton from 'Components/utils/styles/roundedButton';
import useIcon from 'Components/utils/hooks/useIcon';
import iconTypes from 'Components/utils/types/iconTypes';
import {
  secondaryColor,
  grayColor,
  notificationColor,
} from 'Themes/utils/colorPickers';
import { textSize } from 'Themes/utils/fontPickers';

const ICON_SIZE = 20;

const iconPosition = ({ width: size }) => css`
  top: 50%;
  margin-top: -${size / 2}px;
  left: 12px;
`;

const inputColors = ({ hasError, disabled }) =>
  hasError
    ? css`
        color: ${notificationColor('error')};
        border-color: ${notificationColor('error')};
      `
    : css`
        color: ${disabled ? grayColor : 'initial'};
        border-color: ${grayColor[0.4]};

        :focus {
          border-color: ${secondaryColor};
        }
      `;

const inputPaddingForIcon = ({ hasIcon }) =>
  hasIcon
    ? css`
        padding-left: 36px;
      `
    : '';

const Wrapper = styled.div`
  position: relative;
`;

const StyledInput = styled.input`
  ${roundedButton}
  ${inputColors}
  text-align: left;
  font-weight: normal;
  ${inputPaddingForIcon};
`;

const Error = styled.span`
  display: block;
  font-size: ${textSize('S')};
  color: ${notificationColor('error')};
  margin: 8px 8px 8px 0;
`;

const useInputChange = (initValue, onChange) => {
  const [value, setValue] = useState(initValue);
  const onChangeHandler = event => {
    setValue(event.target.value);
    if (onChange) {
      onChange(event.target.value);
    }
  };

  return [value, onChangeHandler];
};

const Input = ({
  value: initValue,
  errorMessage,
  icon,
  onChange,
  ...props
}) => {
  const [value, onChangeHandler] = useInputChange(initValue, onChange);
  const Icon = useIcon(icon, ICON_SIZE, iconPosition);

  return (
    <Wrapper {...props}>
      <StyledInput
        type="text"
        value={value}
        hasError={!!errorMessage}
        hasIcon={!!icon}
        onChange={onChangeHandler}
        {...props}
      />
      {errorMessage && <Error>{errorMessage}</Error>}
      <Icon />
    </Wrapper>
  );
};

Input.propTypes = {
  value: PropTypes.string,
  placeholder: PropTypes.string,
  errorMessage: PropTypes.string,
  icon: PropTypes.oneOf(iconTypes),
  small: PropTypes.bool,
  disabled: PropTypes.bool,
  onChange: PropTypes.func,
};

Input.defaultProps = {
  value: '',
  placeholder: '',
  errorMessage: '',
  small: false,
  disabled: false,
};

Input.displayName = 'Input';

export default Input;
