import React from 'react'

import { AuthenticationContext } from '@agiliza/api/domain'
import ImageUpload from '@agiliza/components/organisms/ImageUpload'
import PhoneField from '@agiliza/components/organisms/PhoneField'
import Address, { AddressState } from '@agiliza/components/templates/Address'
import { formatCurrency } from '@agiliza/utils/formatters'
import { ActionType } from '@agiliza/utils/hooks/state'
import { getBase64FromFile } from '@agiliza/utils/method'
import CPFCNPJField from '@agiliza/views/ProposalData/components/atoms/CPFCNPJField'
import { DatePicker } from '@curio/components'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: CustomerSourceIncomeState
  actions: ActionType<CustomerSourceIncomeState>
  context: AuthenticationContext
}

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

  const { cnpj, admissionDate, companyName, proofAddress, mobile, netIncome, address } = state

  const handleChangeDate = (type: keyof Pick<CustomerSourceIncomeState, 'admissionDate'>) => (date: Date | null) => {
    actions.update({ [type]: date })
  }

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

  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({ proofAddress: b64 })
    }
  }

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

  return (
    <form className={classes.form}>
      <TextField variant="outlined" label="Razão social" value={companyName} onChange={handleChangeText('companyName')} />
      <CPFCNPJField value={cnpj} onChange={handleChangeText('cnpj')} onlyCPNJ />
      <DatePicker
        id="admission-date"
        label="Data de admissão"
        value={admissionDate}
        onChange={handleChangeDate('admissionDate')}
        format="dd/MM/yyyy"
        className={classes.datePicker}
      />
      <ImageUpload label="Comprovante" image={proofAddress} onChangeImage={handleChangeProof} />
      <PhoneField value={mobile} onChange={handleChangeText('mobile')} />
      <TextField variant="outlined" label="Renda líquida" value={formatCurrency(netIncome)} onChange={handleChangeText('netIncome')} />
      <Address state={address} onChange={handleChangeAddress} states={context.states} cities={context.cities} />
    </form>
  )
}

export default withStyles(styles)(Form)
