import * as React from 'react';

import TextareaStyle from './Textarea.styled';

export interface IProps {
  feedback?: string|Object;
  placeholder: string;
  isInvalid?: boolean|string;
  isWarning?: boolean|string;
  comment?: string;
  label?: string;
  css?: string|Object;
  passwordType?: boolean;
  onChange: ({ target }: any) => void|any;
  onBlur?: ({ target }: any) => void|any;
  value?: string|number;
  minLength?: number;
  maxLength?: number;
  name?: string;
  min?: string;
  max?: string;
  disabled?: boolean;
  rows?: number;
}

export default class Textarea extends React.PureComponent<IProps> {
  state = {
    value: '',
    rows: 1,
    minRows: 1
  }

  onChange = ({ currentTarget }: React.SyntheticEvent<HTMLTextAreaElement>) => {
    const textareaLineHeight = 22;
    const { minRows } = this.state;
		
		const previousRows = currentTarget.rows;
  	currentTarget.rows = minRows;
		
		const currentRows = ~~(currentTarget.scrollHeight / textareaLineHeight);
    
    if (currentRows === previousRows) {
    	currentTarget.rows = currentRows;
    }
    
    this.props.onChange(currentTarget);
  	this.setState({
    	value: currentTarget.value,
      rows: currentRows,
    });
  }
  
  render () {
    const { feedback, comment, label, placeholder, isInvalid, isWarning } = this.props;
    const moreInformationInInput = feedback || comment || isInvalid || isWarning;

    return (
      <TextareaStyle.GroupInput>
        <TextareaStyle.Textarea
          {...this.props}
          value={this.state.value}
          onChange={this.onChange}
          rows={this.state.rows}
        />
        <label>{label || placeholder}</label>
        <span className='bar' />
        {(moreInformationInInput) && <span className='feedback'>{moreInformationInInput}</span>}
      </TextareaStyle.GroupInput>
    );
  }
}
