import React, { forwardRef } from 'react'
import DatePicker, { ReactDatePickerProps, registerLocale } from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
import './DateInput.web.css'
import hu from 'date-fns/locale/hu'
import { useField, useFormikContext } from 'formik'
import { Box, Input } from 'native-base'
const moment = require('moment')
import { FormControl as NBFormControl, Text } from 'native-base'

registerLocale('hu', hu)

type DateInputProps = {
  label?: string
  name?: any
  disabled?: boolean
  pickerProps?: ReactDatePickerProps
}

function DateInput(props: DateInputProps) {
  const [field, { error }] = useField(props.name)
  const { setFieldValue }: any = useFormikContext()

  function onChange(date: Date) {
    setFieldValue(field.name, date ? moment(date).toISOString() : null)
  }

  const dateInputDisabled = typeof props.disabled === 'undefined' ? false : props.disabled
  const CustomInputField = forwardRef((props: any, ref) => {
    return (
      <Input
        autoCompleteType={'off'} // don't show suggestion popups, those would cover the date pickup
        ref={ref}
        defaultValue={props.value}
        value={props.value}
        // @ts-ignore: use HTML onClick directly
        onClick={props.onClick}
        w={'100%'}
        // In case of error, this is some red
        borderColor={props.borderColor}
        disabled={dateInputDisabled}
      />
    )
  })

  const selected = field.value && field.value.length ? moment(field.value).toDate() : null

  return (
    <>
      <Box mt={4} />
      {props.name && <NBFormControl.Label>{props.label}</NBFormControl.Label>}
      <DatePicker
        selected={selected}
        onChange={onChange}
        locale="hu"
        showTimeSelect
        timeFormat="p"
        timeCaption={'Idő'}
        timeIntervals={15}
        dateFormat="Pp"
        minDate={new Date()}
        customInput={<CustomInputField borderColor={error ? 'red.500' : null} />}
        //inline
        {...props}
      />
      {error && <Text color={'red.500'}>{error}</Text>}
    </>
  )
  // We actually should have it wrapped in a FormControl, however in this case when popper is shown downward
  // it goes beneath the other form elements. An upward popup is always OK ...
  // So we work it aroung above using our own control mechanism for displaying error state.
  // return (
  //   <FormControl name={props.name} label={props.label}  mt={4}>
  //     <DatePicker
  //       selected={field.value && field.value.length ? moment(field.value).toDate() : null}
  //       onChange={onChange}
  //       locale="hu"
  //       showTimeSelect
  //       timeFormat="p"
  //       timeIntervals={15}
  //       dateFormat="Pp"
  //       minDate={new Date()}
  //       // popperPlacement={"auto-start"}
  //       customInput={<CustomInput />}
  //       {...props}
  //     />
  // </FormControl>
  // );
}

export default DateInput
