import React from 'react'

import { RG } from '@agiliza/api/domain'
import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import { maskRG } from '@agiliza/utils/masks'
import { 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 {
  rg?: RG
  onChange: (rg: Partial<RG>) => void
}

const RGTemplate = (props: Props) => {
  const { classes, rg, onChange } = props

  const handleChangePhoto =
    (key: keyof Pick<RG, 'front' | 'back'>): React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>['onChange'] =>
    async (evt) => {
      const file = evt.target.files && evt.target.files[0]
      if (file) {
        const b64 = await getBase64FromFile(file)
        onChange({ [key]: b64 })
      }
    }

  const handleChangeField =
    (key: keyof RG): TextFieldProps['onChange'] =>
    (evt) => {
      onChange({ [key]: evt.target.value })
    }

  return (
    <div className={classes.container}>
      <div className={classes.imagesContainer}>
        <ImageUpload label="Frente" image={rg?.front} onChangeImage={handleChangePhoto('front')} className={classes.imageUpload} />
        <ImageUpload label="Verso" image={rg?.back} onChangeImage={handleChangePhoto('back')} className={classes.imageUpload} />
      </div>
      <TextField
        variant="outlined"
        label="Número do RG"
        value={maskRG(rg?.number || '')}
        onChange={handleChangeField('number')}
        inputProps={{ maxLength: 9 }}
      />
      <TextField variant="outlined" label="Órgão Exp." value={rg?.dispatcherAgency || ''} onChange={handleChangeField('dispatcherAgency')} />
    </div>
  )
}

export default withStyles(styles)(RGTemplate)
