import * as React from 'react'
import DatePicker from 'rc-calendar/lib/Picker'
import RcCalendar from 'rc-calendar/lib/Calendar'
import 'rc-calendar/assets/index.css'
import closest from '../../helpers'
import { TextInput } from '../TextInput'
import { CalendarWrapper, InputWrapper, Wrapper } from './styles'
import { IconCalendar } from './IconCalendar'

// tslint:disable-next-line
const moment = require('moment')

type CalendarProps = {
  onChange: (...args: any[]) => any
  placeholder?: string
  value?: string | any
  name?: string
  dateFormat?: string
  invalid?: boolean
  defaultOpen?: boolean
}

type CalendarState = {
  isOpen: any
}

export class Calendar extends React.Component<CalendarProps, CalendarState> {
  static defaultProps = {
    dateFormat: 'YYYY-MM-DD',
    invalid: false,
    defaultOpen: false,
    value: null,
    placeholder: '',
  }

  constructor(props) {
    super(props)
    this.state = {
      isOpen: props.defaultOpen,
    }
  }

  containerRef

  componentDidMount() {
    document.addEventListener('mousedown', this.onDocumentMouseDown)
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.onDocumentMouseDown)
  }

  onDocumentMouseDown = ({ target }) => {
    if (this.state.isOpen) {
      if (!closest(target, this.containerRef)) {
        this.setState({ isOpen: false })
      }
    }
  }

  onChange = value => {
    this.props.onChange(value, this.props.name)
    this.setState({ isOpen: false })
  }

  onOpen = () => this.setState({ isOpen: true })

  setContainerRef = container => {
    this.containerRef = container
  }

  getContainerRef = () => this.containerRef

  render() {
    const { placeholder, value, dateFormat, invalid } = this.props
    return (
      <Wrapper>
        <CalendarWrapper>
          <div ref={this.setContainerRef}>
            <DatePicker
              getCalendarContainer={this.getContainerRef}
              calendar={
                <RcCalendar
                  formatter={dateFormat}
                  onChange={this.onChange}
                  dateInputPlaceholder={placeholder}
                />
              }
              value={value ? moment(value) : null}
              open={this.state.isOpen}
            >
              {params => (
                <InputWrapper onClick={this.onOpen}>
                  <span>
                    <TextInput
                      placeholder={placeholder}
                      readOnly
                      invalid={invalid}
                      value={params.value ? params.value.format(dateFormat) : ''}
                    />
                    <IconCalendar />
                  </span>
                </InputWrapper>
              )}
            </DatePicker>
          </div>
        </CalendarWrapper>
      </Wrapper>
    )
  }
}
