import { useField } from 'formik'
import React from 'react'
import StringMask from 'string-mask'
import TextField from '@material-ui/core/TextField'

const DELIMITER = '-'
const MASK = '000-000-0000'

function removeTrailingCharIfFound(str: string, char): string {
  return str
    .split(char)
    .filter(segment => segment !== '')
    .join(char)
}

function formatValue(str: string): string {
  const formatter = new StringMask(MASK)
  const unmaskedValue = str.split(DELIMITER).join('')
  const formatted = formatter.apply(unmaskedValue)
  const cleanFormatted = removeTrailingCharIfFound(formatted, DELIMITER)
  return cleanFormatted
}

const PhoneField = props => {
  const { name, validate, ...other } = props
  const [field, meta] = useField({ name, validate })
  const { onChange, ...otherField } = field
  const fieldError = meta.error
  const showError = meta.touched && !!fieldError

  return (
    <TextField
      {...other}
      {...otherField}
      variant="outlined"
      fullWidth
      error={showError}
      helperText={showError ? fieldError : props.helperText}
      onChange={event => {
        onChange(event.target.name)(formatValue(event.target.value))
      }}
    />
  )
}

export default PhoneField