import React from 'react'

import { BanestesAccount } from '@agiliza/api/domain'
import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import { extractNumbers, getBase64FromFile } from '@agiliza/utils/method'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import styles from './styles'

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  values: BanestesAccount
  onChanges: {
    account: (type: keyof BanestesAccount) => TextFieldProps['onChange']
    photo: (name: string) => void
    validState?: (validState: boolean) => void
  }
}

const AccountInputsPhoto = (props: Props) => {
  const { classes, values, onChanges } = props
  const { agencyNumber, cardPicture, number } = values

  const handleChangeField = (type: keyof BanestesAccount): TextFieldProps['onChange'] => onChanges.account(type)

  const handleChangePhoto: 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)
      onChanges.photo(b64)
    }
  }

  return (
    <div className={classes.accountInputsPhotoContainer}>
      <div className={classes.accountInputsContainer}>
        <TextField
          label="Número da agência"
          value={extractNumbers(agencyNumber) || ''}
          onChange={handleChangeField('agencyNumber')}
          variant="outlined"
        />
        <TextField label="Número da conta corrente" value={extractNumbers(number) || ''} onChange={handleChangeField('number')} variant="outlined" />
      </div>
      <ImageUpload label="Foto cartão" image={cardPicture} onChangeImage={handleChangePhoto} />
    </div>
  )
}

export default withStyles(styles)(AccountInputsPhoto)
