import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames/bind';
import { Eye, EyeOff } from 'react-feather';
import styles from './input.scss';
import Closeable from '../Utilities/Closeable';
import Typography from '../Typography';

const Input = ({
  placeholder,
  message,
  danger,
  success,
  defaultValue,
  name,
  onChange,
  clearable,
  password,
  label,
  icon,
  disabled,
  block,
}) => {
  const cx = classnames.bind(styles);

  const { Text } = Typography;

  const [value, setValue] = useState(defaultValue);
  const [type, setType] = useState(password ? 'password' : 'input');

  const handleChange = newValue => {
    setValue(newValue);
    onChange(newValue);
  };

  return (
    <div
      className={cx('input', {
        input__block: block,
      })}
    >
      {label && <Text bold>{label}</Text>}

      <div
        className={cx('input__wrapper', {
          input__wrapper__success: success,
          input__wrapper__danger: danger,
          input__wrapper__disabled: disabled,
        })}
      >
        {icon && <span className={cx('input__icon')}>{icon}</span>}

        <input
          onChange={newValue => handleChange(newValue.target.value)}
          value={value}
          tabIndex={0}
          className={cx('input__container')}
          placeholder={placeholder}
          type={type}
          name={name}
        />

        {clearable && value !== '' && (
          <Closeable onClick={() => handleChange('')} />
        )}

        {password && (
          <span
            className={cx('input__eye')}
            role="button"
            tabIndex={0}
            onClick={() => setType(type === 'password' ? 'input' : 'password')}
            onKeyPress={() =>
              setType(type === 'password' ? 'input' : 'password')
            }
          >
            {type === 'password' ? <Eye size={16} /> : <EyeOff size={16} />}
          </span>
        )}
      </div>

      {message && (
        <span
          className={cx('input__message', {
            input__message__success: success,
            input__message__danger: danger,
          })}
        >
          {message}
        </span>
      )}
    </div>
  );
};

Input.defaultProps = {
  placeholder: undefined,
  message: undefined,
  danger: false,
  success: false,
  defaultValue: '',
  onChange: () => {},
  clearable: false,
  password: false,
  label: undefined,
  icon: undefined,
  disabled: false,
  block: false,
};

Input.propTypes = {
  placeholder: PropTypes.string,
  message: PropTypes.string,
  danger: PropTypes.bool,
  success: PropTypes.bool,
  defaultValue: PropTypes.string,
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func,
  clearable: PropTypes.bool,
  password: PropTypes.bool,
  label: PropTypes.string,
  icon: PropTypes.node,
  disabled: PropTypes.bool,
  block: PropTypes.bool,
};

export default Input;
