import { FieldProps } from 'formik'
import * as React from 'react'
import DateTimePicker from 'react-native-modal-datetime-picker'
import { HelperText, TextInput } from 'react-native-paper'
import moment from 'moment'

interface IInputDateProps extends FieldProps {
  label: string
  format?: string
  mode?: 'date' | 'time' | 'datetime'
}

interface IInputDateState {
  isDateTimePickerVisible: boolean
}

export class InputDate extends React.Component<IInputDateProps, IInputDateState> {
  state = {
    isDateTimePickerVisible: false,
  }
  show = () =>
    this.setState({ isDateTimePickerVisible: true })

  hide = () =>
    this.setState({ isDateTimePickerVisible: false })

  render() {
    const {
      label,
      field,
      form,
      format,
      mode,
    } = this.props
    const {
      touched,
      errors,
      setFieldValue,
    } = form
    const {
      name,
      value,
    } = field

    return (
      <>
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          mode={mode}
          onConfirm={date => {
            setFieldValue(name, date)
            this.hide()
          }}
          onCancel={this.hide}
        />
        <TextInput
          mode={'outlined'}
          label={label}
          onFocus={this.show}
          error={!!errors[name]}
          value={moment(value).format(format || 'DD/MM/YYYY')}
        />
        <HelperText type="error" visible={!!touched[name]}>
          {errors[name]}
        </HelperText>
      </>
    )
  }
}
