import React from 'react'

import { IPAddress } from '@agiliza/api/domain'
import { maskCEP } from '@agiliza/utils/masks'
import { extractNumbers } from '@agiliza/utils/method'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import { AddressState } from './state'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: AddressState
  onChange: (address: Partial<IPAddress>) => void
}

const Address = (props: Props) => {
  const { state, onChange } = props

  const { cep, number, street } = state

  const handleChangeText =
    (key: keyof AddressState): TextFieldProps['onChange'] =>
    (evt) => {
      onChange({ [key]: evt.target.value })
    }
  return (
    <>
      <TextField variant="outlined" label="CEP" value={maskCEP(cep)} onChange={handleChangeText('cep')} inputProps={{ maxLength: 9 }} />
      <TextField variant="outlined" label="Rua / Avenida" value={street} onChange={handleChangeText('street')} />
      <TextField variant="outlined" label="Number" value={extractNumbers(number)} onChange={handleChangeText('number')} type="tel" />
    </>
  )
}

export default withStyles(styles)(Address)
