import React from 'react'

import { AuthenticationContext } from '@agiliza/api/domain'
import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import AddressTemplate from '@agiliza/components/templates/Address'
import { ActionType } from '@agiliza/utils/hooks/state'
import { getBase64FromFile } from '@agiliza/utils/method'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: BDAddressState
  actions: ActionType<BDAddressState>
  context: AuthenticationContext
}

const Form = (props: Props) => {
  const { classes, state: _state, actions, context } = props

  const { cep, number, street, city, complement, district, state, referencePoint, proof } = _state

  const handleChangeText =
    (key: keyof BDAddressState): TextFieldProps['onChange'] =>
    (evt) => {
      actions.update({ [key]: evt.target.value })
    }

  const handleChangeProof: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>['onChange'] = async (evt) => {
    const file = evt.target.files && evt.target.files[0]
    if (file) {
      const b64: string = await getBase64FromFile(file)
      actions.update({ proof: b64 })
    }
  }

  return (
    <form className={classes.form}>
      <ImageUpload label="Comprovante de residência" image={proof} onChangeImage={handleChangeProof} />
      <AddressTemplate
        states={context.states}
        cities={context.cities}
        state={{ cep, number, street, city, complement, district, state }}
        onChange={(addrs) => actions.update(addrs)}
      />
      <TextField variant="outlined" label="Ponto de referência" value={referencePoint} onChange={handleChangeText('referencePoint')} />
    </form>
  )
}

export default withStyles(styles)(Form)
