import React from 'react'

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

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

type ExtendedProps = WithStyles<typeof styles>

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

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

  const { proof } = state

  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 })
    }
  }

  const handleChangeAddress = (value: Partial<AddressState>) => {
    actions.update(value)
  }

  return (
    <form className={classes.form}>
      <ImageUpload label="Comprovante de residência" image={proof} onChangeImage={handleChangeProof} />
      <Address state={state} onChange={handleChangeAddress} states={states} cities={cities} />
    </form>
  )
}

export default withStyles(styles)(Form)
