import React from 'react'

import { maskCNPJ, maskCPFCNPJ } from '@agiliza/utils/masks'
import { TextField, TextFieldProps } from '@material-ui/core'

type ExtendedProps = Record<string, unknown> & Pick<TextFieldProps, 'value' | 'onChange' | 'disabled'>

interface Props extends ExtendedProps {
  onlyCPF?: boolean
  onlyCPNJ?: boolean
  label?: string
}

const CPFCNPJField = (props: Props) => {
  const { onlyCPF, onlyCPNJ, label = 'CPF', value, ...textFieldProps } = props
  const getLabel = () => (onlyCPF ? 'CPF' : onlyCPNJ ? 'CNPJ' : 'CPF / CNPJ')
  return (
    <TextField
      type="tel"
      variant="outlined"
      inputProps={{ maxLength: onlyCPF ? 14 : 18 }}
      label={getLabel()}
      value={onlyCPF ? maskCPFCNPJ((value as string) || '') : maskCNPJ((value as string) || '')}
      {...textFieldProps}
    />
  )
}

export default CPFCNPJField
