import React from 'react'

import { ProposalDataContext } from '@agiliza/api/domain'
import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import PhoneField from '@agiliza/components/organisms/PhoneField'
import { ActionType } from '@agiliza/utils/hooks/state'
import { getBase64FromFile } from '@agiliza/utils/method'
import { SelectField, SelectFieldProps } from '@curio/components'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: CDReferenceState
  actions: ActionType<CDReferenceState>
  context: ProposalDataContext
}

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

  const { name, telephone, photo, type, extraInfo, concept } = state

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

  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)
      actions.update({ photo: b64 })
    }
  }

  const handleChangeSelect =
    (key: keyof Pick<CDReferenceState, 'type'>): SelectFieldProps['onChange'] =>
    (value) => {
      actions.update({ [key]: value })
    }

  return (
    <form className={classes.form}>
      <ImageUpload label="Foto da referência" image={photo} onChangeImage={handleChangePhoto} />
      <SelectField
        id="type-select"
        variant="outlined"
        label="Tipo"
        value={type}
        onChange={handleChangeSelect('type')}
        items={context.referenceTypes.map((st) => ({ label: st.description, value: st.id }))}
        shrink={false}
        // className={classes.selectField}
      />
      <TextField variant="outlined" label="Nome" value={name} onChange={handleChangeText('name')} />
      <PhoneField value={telephone} onChange={handleChangeText('telephone')} />
      <TextField variant="outlined" label="Outras informações" value={extraInfo} onChange={handleChangeText('extraInfo')} />
      <TextField variant="outlined" label="Conceito" value={concept} onChange={handleChangeText('concept')} />
    </form>
  )
}

export default withStyles(styles)(Form)
