import React from 'react'

import { City, State } from '@agiliza/api/domain/authentication'
import PhoneField from '@agiliza/components/organisms/PhoneField'
import { useErrorValidator } from '@agiliza/utils/hooks/errorValidation'
import { ActionType } from '@agiliza/utils/hooks/state'
import CPFCNPJField from '@agiliza/views/ProposalData/components/atoms/CPFCNPJField'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import AddressForm, { AddressState } from '../Address'
import { initState, State as FirstAccessState } from './state'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  states: State[]
  cities: City[]
  state: FirstAccessState
  actions: ActionType<FirstAccessState>
}

const FirstAccess = (props: Props) => {
  const { classes, states, cities, state, actions } = props

  const { cpf, name, email, phone, ...addressState } = state

  const { actions: errorActions } = useErrorValidator(initState)

  const handleChange =
    (key: keyof FirstAccessState): TextFieldProps['onChange'] =>
    (evt) => {
      actions.update({ [key]: evt.target.value })
      errorActions.validate({ [key]: evt.target.value })
    }
  const handleChangeAddress = (value: Partial<AddressState>) => {
    actions.update(value)
  }

  return (
    <form className={classes.form}>
      <CPFCNPJField value={cpf} onChange={handleChange('cpf')} onlyCPF disabled />
      <TextField variant="outlined" label="Nome" value={name} onChange={handleChange('name')} />
      <TextField variant="outlined" label="Email" value={email} onChange={handleChange('email')} />
      <PhoneField value={phone} onChange={handleChange('phone')} />
      <AddressForm state={addressState} onChange={handleChangeAddress} states={states} cities={cities} />
    </form>
  )
}

export default withStyles(styles)(FirstAccess)
