import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import moment from 'moment'
import {
  compose,
  identity,
  omit,
  path,
  test,
} from 'ramda'
import cx from 'classnames'
import { CalendarDuo } from '@northlight/icons'

import MTAnimation from './mt-animation'
import MTRangePickerMenu from './mt-range-picker-menu'

const getTargetClassNames = path([ 'target', 'className' ])
const isPikaClassName = test(/^pika/)
const isPikadayEvent = compose(isPikaClassName, getTargetClassNames)
const shouldHandleOutsideClick = (e) => !isPikadayEvent(e)

const DATE_FORMAT = 'YYYY-MM-DD'
const defaultYearStart = {
  month: 0,
  day: 1,
}
const TAB = 9

const getFormattedValue = function (val, format) {
  return val === '' ? '' : moment(val).format(format)
}
function isInsideElement (e1, e2) {
  if (e1 === null) {
    return false
  }
  return e1 === e2 || isInsideElement(e1.parentNode, e2)
}

class MTRangePicker extends Component {
  constructor (props) {
    super(props)

    this.state = {
      startDate: props.initialStartDate,
      endDate: props.initialEndDate,
      menuVisible: false,
    }

    this.handleKeyDown = this.handleKeyDown.bind(this)
    this.onOutsideClick = this.onOutsideClick.bind(this)
    this._outsideClickListener = this._outsideClickListener.bind(this)
    this.listenForOutsideClick = this.listenForOutsideClick.bind(this)
    this.stopListenForOutsideClick = this.stopListenForOutsideClick.bind(this)
    this.reset = this.reset.bind(this)
    this.close = this.close.bind(this)
    this.show = this.show.bind(this)
    this.toggleMenu = this.toggleMenu.bind(this)
    this.updateValues = this.updateValues.bind(this)
    this.selectDateRange = this.selectDateRange.bind(this)
    this.updateStartValue = this.updateStartValue.bind(this)
    this.updateEndValue = this.updateEndValue.bind(this)
    this.clearRange = this.clearRange.bind(this)
  }

  UNSAFE_componentWillReceiveProps (nextProps) {
    this.setState({
      startDate: nextProps.initialStartDate,
      endDate: nextProps.initialEndDate,
    })
  }

  UNSAFE_componentWillUpdate (_, nextState) {
    if (nextState.menuVisible) {
      this.listenForOutsideClick()
    }
  }

  componentWillUnmount () {
    this.stopListenForOutsideClick()
  }

  handleKeyDown (e) {
    const keyCode = e.keyCode || e.which
    if (keyCode === TAB) {
      this.close()
    }
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  onOutsideClick () {
    if (this.state.startDate === '' || this.state.endDate === '') {
      this.reset()
    } else {
      this.selectDateRange()
    }
    this.close()
  }

  _outsideClickListener (e) {
    /* eslint-disable react/no-find-dom-node */
    if (!isInsideElement(e.target, ReactDOM.findDOMNode(this))) {
      if (shouldHandleOutsideClick(e)) {
        this.onOutsideClick(e)
      }
    }
  }

  listenForOutsideClick () {
    document.addEventListener('mousedown', this._outsideClickListener)
  }

  stopListenForOutsideClick () {
    document.removeEventListener('mousedown', this._outsideClickListener)
  }

  reset () {
    this.setState({
      startDate: this.props.initialStartDate,
      endDate: this.props.initialEndDate,
    })
  }

  close () {
    this.setState({ menuVisible: false })
    this.stopListenForOutsideClick()
  }

  show () {
    this.setState({ menuVisible: true })
    this.listenForOutsideClick()
  }

  toggleMenu () {
    if (this.state.startDate !== '' && this.state.endDate !== '') {
      this.selectDateRange()
    }
    this.setState((previousState) => ({
      ...previousState,
      menuVisible: !previousState.menuVisible,
    }))
  }

  updateValues (dates) {
    const startDateConverted = moment(dates.startDate, DATE_FORMAT).toDate()
    const endDateConverted = moment(dates.endDate, DATE_FORMAT).toDate()
    this.setState({ startDate: dates.startDate, endDate: dates.endDate })
    this.props.whenChanged(startDateConverted, endDateConverted)
  }

  selectDateRange () {
    const startDateConverted = moment(this.state.startDate, DATE_FORMAT).toDate()
    const endDateConverted = moment(this.state.endDate, DATE_FORMAT).toDate()
    this.props.whenSelected(startDateConverted, endDateConverted)
    this.close()
  }

  updateStartValue (startDate) {
    const endDate = startDate > this.state.endDate ? startDate : this.state.endDate
    this.updateValues({ startDate, endDate })
  }

  updateEndValue (endDate) {
    const startDate = endDate < this.state.startDate ? endDate : this.state.startDate
    this.updateValues({ startDate, endDate })
  }

  clearRange (e) {
    e.stopPropagation()
    this.setState({ startDate: '', endDate: '' })
    this.props.whenChanged(null, null)
  }

  render () {
    const { startDate, endDate, menuVisible } = this.state
    const {
      dateFormat,
      placeholder,
      label,
      showClearControls,
      tabIndex,
      iconTriggerOnly,
      disabled,
      size,
      ...rest
    } = this.props
    const otherProps = omit([
      'initialStartDate',
      'initialEndDate',
      'whenChanged',
      'whenSelected',
      'menuPosition',
      'firstDay',
      'showSelectControls',
      'setDefaultDate',
      'initialDateString',
      'yearStart',
      'quarterPrefix',
      'customYearLabel',
    ], rest)

    const valueString = startDate !== '' || endDate !== ''
      ? `${getFormattedValue(startDate, dateFormat)} - ${getFormattedValue(endDate, dateFormat)}`
      : <span className="range-picker__placeholder">{ placeholder }</span>

    const clearControls = showClearControls && (startDate !== '' || endDate !== '')
      ? <span onClick={ this.clearRange } className="icon-close m-l pull-right" />
      : null

    const triggerClasses = cx(`range-picker__trigger size-${size}`, {
      'is-active': menuVisible,
    })

    const pickerMenu = (
      <MTAnimation
        enterDuration="instant"
        leaveDuration="instant"
        enterAnimationClass="fadeInTop"
        leaveAnimationClass="fadeOutTop"
        show={ this.state.menuVisible }
      >
        <MTRangePickerMenu
          { ...this.props }
          updateValues={ this.updateValues }
          selectDateRange={ this.selectDateRange }
          startDate={ startDate }
          endDate={ endDate }
          updateStartValue={ this.updateStartValue }
          updateEndValue={ this.updateEndValue }
        />
      </MTAnimation>
    )

    const iconPicker = (
      <span className={ `range-picker ${disabled ? 'disabled' : ''}` }>
        <div style={ { width: '20px', height: '20px' } }>
          <CalendarDuo
            onClick={ disabled ? null : this.toggleMenu }
            viewBox="0 0 24 24"
            width="100%"
            height="100%"
            style={ {
              paddingLeft: '2x',
              paddingRight: '2px',
            } }
          />
        </div>
        { pickerMenu }
      </span>
    )

    const inputPicker = (
      <div className="range-picker__input input">
        <label className="top-label" onClick={ disabled ? null : this.toggleMenu }>
          <bdi>{ label }</bdi>
        </label>
        <div className="range-picker">
          { disabled
            ? (
              <span
                className="range-picker__trigger disabled"
              >
                { valueString }
                <div style={ { width: '20px', height: '20px' } }>
                  <CalendarDuo
                    viewBox="0 0 24 24"
                    width="100%"
                    height="100%"
                    style={ {
                      paddingLeft: '2x',
                      paddingRight: '2px',
                    } }
                  />
                </div>
              </span>
            )
            : (
              <span
                className={ triggerClasses }
                onFocus={ this.show }
                onKeyDown={ this.handleKeyDown }
                tabIndex={ tabIndex }
              >
                { valueString }
                <div style={ { width: '20px', height: '20px' } }>
                  <CalendarDuo
                    viewBox="0 0 24 24"
                    width="100%"
                    height="100%"
                    style={ {
                      paddingLeft: '2x',
                      paddingRight: '2px',
                    } }
                  />
                  { clearControls }
                </div>
              </span>
            )
          }
          { pickerMenu }
        </div>
      </div>
    )

    return (
      <span { ...otherProps }>
        { iconTriggerOnly
          ? iconPicker
          : inputPicker
        }
      </span>
    )
  }
}

MTRangePicker.defaultProps = {
  menuPosition: 'right',
  label: '',
  initialStartDate: '',
  initialEndDate: '',
  firstDay: 0,
  dateFormat: 'YYYY-MM-DD',
  placeholder: 'Select date range',
  whenChanged: identity,
  whenSelected: identity,
  showSelectControls: false,
  setDefaultDate: true,
  initialDateString: '',
  yearStart: defaultYearStart,
  quarterPrefix: '',
  customYearLabel: 'fiscal year',
  showClearControls: false,
  tabIndex: '0',
  iconTriggerOnly: false,
  size: 'sm',
}

MTRangePicker.propTypes = {
  menuPosition: PropTypes.oneOf([ 'left', 'right' ]),
  label: PropTypes.string,
  initialStartDate: PropTypes.string,
  initialEndDate: PropTypes.string,
  firstDay: PropTypes.number,
  dateFormat: PropTypes.string,
  placeholder: PropTypes.string,
  whenChanged: PropTypes.func,
  whenSelected: PropTypes.func,
  showSelectControls: PropTypes.bool,
  setDefaultDate: PropTypes.bool,
  initialDateString: PropTypes.string,
  yearStart: PropTypes.shape({
    month: PropTypes.number,
    day: PropTypes.number,
  }),
  quarterPrefix: PropTypes.string,
  customYearLabel: PropTypes.string,
  showClearControls: PropTypes.bool,
  tabIndex: PropTypes.string,
  iconTriggerOnly: PropTypes.bool,
  size: PropTypes.oneOf([ 'sm', 'md' ]),
}

export default MTRangePicker
