import React, { useMemo } from 'react'

import { City, State } from '@agiliza/api/domain'
import { maskCEP } from '@agiliza/utils/masks'
import { SelectField, SelectFieldProps } from '@curio/components'
import { TextField, TextFieldProps } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  states: State[]
  cities: City[]
  state: AddressState
  onChange: (address: Partial<AddressState>) => void
}

const Address = (props: Props) => {
  const { classes, state: _state, onChange, states, cities } = props

  const { cep, street, number, complement, state, city, district } = _state

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

  const handleChangeSelect =
    (key: keyof AddressState): SelectFieldProps['onChange'] =>
    (value) => {
      onChange({ [key]: value })
    }

  const availableCities = useMemo(() => {
    if (state === '') return []
    return cities.filter((ct) => ct.state === state)
  }, [state])

  return (
    <>
      <TextField variant="outlined" label="CEP" value={maskCEP(cep)} onChange={handleChange('cep')} inputProps={{ maxLength: 9 }} />
      <TextField variant="outlined" label="Rua / Avenida" value={street} onChange={handleChange('street')} />
      <TextField variant="outlined" label="Número" type="tel" value={number} onChange={handleChange('number')} />
      <TextField variant="outlined" label="Complemento" value={complement} onChange={handleChange('complement')} />
      <SelectField
        id="state-select"
        variant="outlined"
        label="Estado"
        value={state}
        onChange={handleChangeSelect('state')}
        items={states.map((st) => ({ label: st.name, value: st.id }))}
        shrink={false}
        className={classes.selectField}
      />
      <SelectField
        id="state-select"
        variant="outlined"
        disabled={!state}
        label="Cidade"
        value={city}
        onChange={handleChangeSelect('city')}
        items={availableCities.map((st) => ({ label: st.name, value: st.id }))}
        shrink={false}
        className={classes.selectField}
      />
      <TextField variant="outlined" label="Bairro" value={district} onChange={handleChange('district')} />
    </>
  )
}

export default withStyles(styles)(Address)
