import React from 'react'

import { ProposalDataContext } from '@agiliza/api/domain'
import DocumentTemplate from '@agiliza/components/templates/Document'
import { ActionType } from '@agiliza/utils/hooks/state'
import { getBase64FromFile } from '@agiliza/utils/method'
import CPFCNPJField from '@agiliza/views/ProposalData/components/atoms/CPFCNPJField'
import { DatePicker, SelectField, SelectFieldProps } from '@curio/components'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

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

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

  const {
    cnpj,
    openingDate,
    stateRegistration,
    cityRegistration,
    fantasyName,
    commercialRegistration,
    activitySector,
    settledOP,
    local,
    codeCNAE,
    mainActivity,
    document,
  } = state

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

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

  const handleChangeSelect =
    (key: keyof BDIdentificationState): SelectFieldProps['onChange'] =>
    (vl) => {
      actions.update({ [key]: vl })
    }

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

  const handleChangeDocumentType = (value: string) => {
    const documentType = context.documentTypes.find((dT) => dT.id === value)
    if (documentType) actions.update({ document: { type: documentType } })
  }

  return (
    <form className={classes.form}>
      <DocumentTemplate document={document} context={context} onChangeImage={handleChangeProof} onChangeDocumentType={handleChangeDocumentType} />
      <CPFCNPJField value={cnpj} onChange={handleChangeText('cnpj')} onlyCPNJ />
      <DatePicker
        id="admission-date"
        label="Data da abertura"
        value={openingDate}
        onChange={handleChangeDate('openingDate')}
        format="dd/MM/yyyy"
        className={classes.datePicker}
      />
      <TextField variant="outlined" label="Inscrição estadual" value={stateRegistration} onChange={handleChangeText('stateRegistration')} />
      <TextField variant="outlined" label="Inscrição municipal" value={cityRegistration} onChange={handleChangeText('cityRegistration')} />
      <TextField variant="outlined" label="Nome fantasia" value={fantasyName} onChange={handleChangeText('fantasyName')} />
      <TextField
        variant="outlined"
        label="Inscrição comercial"
        value={commercialRegistration}
        onChange={handleChangeText('commercialRegistration')}
      />
      <SelectField
        id="activity-sector-select-field"
        label="Setor de atividade"
        value={activitySector}
        onChange={handleChangeSelect('activitySector')}
        items={context.activitySectors.map((aS) => ({ label: aS.description, value: aS.id }))}
        variant="outlined"
        shrink={false}
      />
      <SelectField
        id="settled-op-select-field"
        label="Op. liquidadas (NC)"
        value={settledOP}
        onChange={handleChangeSelect('settledOP')}
        items={context.settledOPs.map((sOP) => ({ label: sOP.description, value: sOP.id }))}
        variant="outlined"
        shrink={false}
      />
      <SelectField
        id="settled-op-select-field"
        label="Local"
        value={local}
        onChange={handleChangeSelect('local')}
        items={context.locals.map((aS) => ({ label: aS.description, value: aS.id }))}
        variant="outlined"
        shrink={false}
      />
      <TextField variant="outlined" type="tel" label="Código CNAE" value={codeCNAE} onChange={handleChangeText('codeCNAE')} />
      <TextField variant="outlined" label="Atividade principal" value={mainActivity} onChange={handleChangeText('mainActivity')} />
    </form>
  )
}

export default withStyles(styles)(Form)
