import * as React from 'react'

import { isAndroid } from '../../utils/detect'
import * as Styled from './index.style'

interface Props {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  type?: 'text' | 'tel';
  limit?: number;
  isLast?: boolean;
}

class Input extends React.Component<Props> {
  state = {
    value: this.props.value ?? ''
  }

  element: any

  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      value: e.target.value
    })
    this.props.onChange?.(e.target.value)
  }

  public render() {
    const {
      value
    } = this.state
    const {
      placeholder,
      limit,
      isLast,
      type = 'text'
    } = this.props
    const maxLengthProps: {
      maxLength?: number;
    } = {}
    if (limit) {
      maxLengthProps.maxLength = limit
    }
    return (
      <>
        <Styled.Input
          ref={(ref) => this.element = ref}
          type={type}
          value={value}
          onChange={this.handleChange}
          placeholder={placeholder}
          onFocus={() => {
            if (isAndroid()) {
              if (isLast) {
                this.element.style.marginBottom = '80px'
              }
              setTimeout(() => {
                this.element.scrollIntoView({
                  behavior: 'smooth',
                  block: 'center'
                })
              }, 300)
            }
          }}
          onBlur={() => {
            if (isAndroid() && isLast) {
              this.element.style.marginBottom = '0'
            }
          }}
          {...maxLengthProps}
        />
      </>
    )
  }
}

export default React.memo(Input)