import React from 'react'

import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import { formatCurrency } from '@agiliza/utils/formatters'
import { ActionType } from '@agiliza/utils/hooks/state'
import { maskLicensePlate } from '@agiliza/utils/masks'
import { getBase64FromFile } from '@agiliza/utils/method'
import {
  Checkbox,
  CheckboxProps,
  FormControlLabel,
  FormGroup,
  TextField,
  TextFieldProps
} from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: CDVehicleState
  actions: ActionType<CDVehicleState>
}

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

  const { document, brand, licensePlate, model, year, marketValue, hasOnus, hasInsurance } = state

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

  const handleChangeImage: 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({ document: b64 })
    }
  }

  const handleChangeCheckbox =
    (key: keyof Pick<CDVehicleState, 'hasInsurance' | 'hasOnus'>): CheckboxProps['onChange'] =>
    (_, checked) => {
      actions.update({ [key]: checked })
    }

  return (
    <form className={classes.form}>
      <ImageUpload label="Documento do veículo" image={document} onChangeImage={handleChangeImage} />
      <TextField variant="outlined" label="Modelo" value={model} onChange={handleChangeText('model')} />
      <TextField variant="outlined" label="Marca" value={brand} onChange={handleChangeText('brand')} />
      <TextField
        variant="outlined"
        label="Placa"
        value={maskLicensePlate(licensePlate)}
        onChange={handleChangeText('licensePlate')}
        inputProps={{ maxLength: 8 }}
      />
      <TextField variant="outlined" label="Ano" value={year} onChange={handleChangeText('year')} />
      <TextField variant="outlined" label="Valor de mercado" value={formatCurrency(marketValue)} onChange={handleChangeText('marketValue')} />
      <FormGroup row className={classes.formGroup}>
        <FormControlLabel label="Possui ônus?" control={<Checkbox name="reside" checked={hasOnus} onChange={handleChangeCheckbox('hasOnus')} />} />
        <FormControlLabel
          label="Possui seguro?"
          control={<Checkbox name="reside" checked={hasInsurance} onChange={handleChangeCheckbox('hasInsurance')} />}
        />
      </FormGroup>
    </form>
  )
}

export default withStyles(styles)(Form)
