import React, { memo, useEffect, useLayoutEffect, useRef, useState } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import {
  append,
  compose,
  contains,
  curry,
  dec,
  either,
  equals,
  find,
  has,
  identity,
  inc,
  isEmpty,
  isNil,
  last,
  map,
  path,
  pick,
  pluck,
  prop,
  propEq,
  propOr,
  reject,
  sum,
  take,
  values,
} from 'ramda'
import { VariableSizeList as List } from 'react-window'
import Fuse from 'fuse.js'
import MTLoader from './mt-loader'
import MTIcon from './mt-icon'
import MTSelectSuggestion from './mt-select-suggestion'
import useOutsideClick from './use-outside-click'
import MTSelectSelectionSingle from './mt-select-selection-singlemodern'
import MTSelectSelectionMultiple from './mt-select-selection-multiple'
import clamp from './clamp'

const KEY_CODES = {
  BACKSPACE: 8,
  ENTER: 13,
  ESCAPE: 27,
  UP_ARROW: 38,
  DOWN_ARROW: 40,
}

const SUGGESTIONS_ITEM_PADDING = 4
const SUGGESTION_DEFAULT_HEIGHT = 30
const MAX_DROPDOWN_HEIGHT = 300
const LOADING_SPINNER_HEIGHT = 15

const isEmptyOrNil = either(isEmpty, isNil)

const getCurrent = prop('current')

const MTSelectSelectionAdditional = memo((props) => {
  const { selection, visibleSelectionElements, additionalItemsLabel } = props

  const additionalElements = selection.length - visibleSelectionElements
  const suffix = additionalElements > 1 && !isEmpty(additionalItemsLabel) ? 's' : ''

  return (
    <span className="mt-select-selection-multiple-additional" key="additional">
      <span className="mt-select-selection-multiple-additional__label">
        <strong>+ { additionalElements } { additionalItemsLabel }{ suffix }</strong>
      </span>
    </span>
  )
})

const SelectionLabels = (props) => {
  const {
    selection,
    visibleSelectionElements,
    removeSuggestion,
    getSuggestion,
    searchValue,
    multiple,
  } = props

  // SINGLE
  if (!multiple) {
    const item = getSuggestion(selection[0])
    if (!item) return null

    return (
      <MTSelectSelectionSingle
        hidden={ !isEmpty(searchValue) }
        label={ item.label }
      />
    )
  }

  // MULTIPLE
  return (
    map((id) => {
      const item = getSuggestion(id)

      // Skip invalid items
      if (!item) return null

      return (
        <MTSelectSelectionMultiple
          key={ id }
          label={ item.label }
          onRemove={ () => removeSuggestion(id) }
        />
      )
    }, take(visibleSelectionElements, selection))
  )
}

const Dropdown = (props) => {
  const {
    isVisible,
    suggestions,
    SuggestionTemplate,
    width,
    hasMore,
    onReachBottom,
    checkSelection,
    hoveredIndex,
    chooseSelection,
    supportsMultiple,
    filteredSuggestions,
    isDropdownVisible,
  } = props

  const [ estimatedHeight, setEstimatedHeight ] = useState(MAX_DROPDOWN_HEIGHT)
  const heightMap = useRef({})

  const listContainerRef = useRef(null)
  const listRef = useRef(null)
  const lastHoveredId = useRef(null)

  /**
   * Returns cached height of a suggestion.
   * If there's no cached information about the targeted item, the default value will be returned.
   *
   * @param {string} id
   * @return {number} height of the targeted item
   * */
  const getItemHeight = (id) => propOr(
    SUGGESTION_DEFAULT_HEIGHT,
    id,
    getCurrent(heightMap)
  )

  /**
   * Returns a sum of height of all cached suggestions.
   *
   * @return {number}
   * */
  const getTotalHeight = () => {
    const activeHeights = values(pick(pluck('id', suggestions), getCurrent(heightMap)))
    const totalHeight = sum(activeHeights)

    return clamp(
      SUGGESTION_DEFAULT_HEIGHT,
      MAX_DROPDOWN_HEIGHT,
      totalHeight
    ) + SUGGESTIONS_ITEM_PADDING
  }

  /**
   * Checks if itemHeights cache contains information about targeted item.
   *
   * @param {string} id
   * @return {boolean}
   * */
  const isHeightRecorded = (id) => has(id, getCurrent(heightMap))

  /**
   * Caches height for the passed suggestion.
   *
   * @param {string} id - id of the targeted suggestion.
   * @param {number} newHeight - height value should be cached.
   * */
  const setItemHeight = curry((id, newHeight) => {
    if (!isVisible) return

    getCurrent(heightMap)[id] = newHeight

    const list = getCurrent(listRef)
    if (isVisible && list) list.resetAfterIndex(0)
  })

  useEffect(() => {
    setEstimatedHeight(getTotalHeight())
  }, [ isDropdownVisible ])

  /**
   * Scrolls to the suggestion at the passed index (position).
   *
   * @param {HTMLElement} suggestionNode
   * */
  const scrollToItem = (suggestionNode) => {
    const { parentNode: { parentNode } } = suggestionNode

    const { scrollTop: pScroll, offsetHeight: pHeight } = parentNode
    const { offsetTop: iTop } = suggestionNode

    if (iTop > pScroll + pHeight) {
      // Scrolls to the bottom, so that item would be on the first position
      parentNode.scrollTop = iTop
    } else if (iTop < pScroll) {
      // Scrolls to the top, so that item would be on the last position
      parentNode.scrollTop -= pHeight
    }
  }

  /**
   * Checks user has reached the bottom of the dropdown list and tries
   * to fetch more suggestions.
   *
   * @param {Event} e
   * @summary Handles scroll event for the dropdown list component.
   * @event scroll
   * */
  const handleScroll = (e) => {
    // Extracts elements' position and scroll offset
    const { scrollOffset, scrollDirection } = e
    const { scrollHeight, clientHeight } = getCurrent(listContainerRef)

    // Checks if user has almost reached the end of the list
    const isAtBottom = scrollHeight - clientHeight <= scrollOffset

    const userScrollDowned = scrollDirection === 'forward'

    // Calls the callback to fetch more suggestions
    if (userScrollDowned && isAtBottom) {
      onReachBottom()
    }
  }

  const handleItemsRendered = () => {
    getCurrent(listRef)?.resetAfterIndex(0)
  }

  const handleRequestItemSize = (item) => {
    const { id } = item

    if (isNil(id)) return LOADING_SPINNER_HEIGHT
    return getItemHeight(id)
  }

  const handleRefProvided = curry((id, isHovered, ref) => {
    // Scrolls to the suggestion when user hovers it with keyboard
    if (!isHovered || equals(id, getCurrent(lastHoveredId)) || isNil(ref)) return

    scrollToItem(ref)
    lastHoveredId.current = id
  })

  // eslint-disable-next-line react/no-unstable-nested-components
  const createSuggestionItem = (index) => (style) => {
    const item = suggestions[index]
    const { id, isDisabled } = item
    const isSelected = checkSelection(id)
    const isHovered = equals(hoveredIndex, index)
    const hasUnknownHeight = !isHeightRecorded(id)

    return (
      <MTSelectSuggestion
        key={ id }
        suggestion={ item }
        style={ style }
        isSelected={ isSelected }
        SuggestionTemplate={ SuggestionTemplate }
        isActive={ isHovered }
        isDisabled={ isDisabled }
        ref={ handleRefProvided(id, isHovered) }
        onSelect={ () => chooseSelection(id) }
        isMultiple={ supportsMultiple }
        onHeightCalculated={
          (hasUnknownHeight)
            ? setItemHeight(id)
            : identity
        }
      />
    )
  }

  const spinnerClassName = filteredSuggestions.length === 0 ? 'mt-select-spinner-without-suggestions' : 'mt-select-spinner'

  const spinnerSpec = {
    id: null,
    // eslint-disable-next-line react/no-unstable-nested-components
    component: (style) => (
      <span className={ spinnerClassName } style={ style }>
        <MTLoader />
      </span>
    ),
  }

  const suggestionSpecs = suggestions.map(({ id }, index) => (
    {
      id,
      component: createSuggestionItem(index),
    }
  ))

  const suggestionCreators = hasMore ? append(spinnerSpec, suggestionSpecs) : suggestionSpecs

  const isHidden = !isVisible || isEmpty(suggestionCreators)
  const listClasses = cx('mt-select__suggestions', {
    hidden: isHidden,
  })

  return (
    <List
      onScroll={ handleScroll }
      className={ listClasses }
      height={ estimatedHeight }
      width={ width }
      onItemsRendered={ handleItemsRendered }
      itemSize={ (index) => handleRequestItemSize(suggestionCreators[index]) }
      ref={ listRef }
      outerRef={ listContainerRef }
      itemCount={ suggestionCreators.length }
      itemData={ suggestionCreators }
    >
      { ({ index, style }) => suggestionCreators[index].component(style) }
    </List>
  )
}

const MTSelect = (props) => {
  const {
    SuggestionTemplate,
    additionalItemsLabel,
    clearable,
    disabled,
    emptyMessage,
    filterProps,
    initialSearchInput,
    inputPlaceHolder,
    multiple,
    onSelectionChange,
    selection,
    suggestions,
    visibleSelectionElements,
    width,
    withIcon,
    icon,
    className,
    isLoading,
    hasMore,
    onReachBottom,
    ...otherProps
  } = props

  const [ searchValue, setSearchValue ] = useState(initialSearchInput)
  const [ isDropdownVisible, setIsDropdownVisible ] = useState(false)
  const [ hoveredIndex, setHoveredIndex ] = useState(-1)

  const [ filteredSuggestions, setFilteredSuggestions ] = useState([])

  const [ optimalWidth, setOptimalWidth ] = useState(width || 0)

  const searchInputRef = useRef(null)
  const wrapperRef = useRef(null)
  const fuseInstance = useRef(null)

  /**
 * Returns id of the last element in the values array.
 *
 * @return {string|null}
 * */
  const getLastSelectedId = () => last(selection)

  /**
 * Checks if suggestion with the passed id is currently hovered.
 *
 * @param {string} id
 * */
  const checkSelection = (id) => contains(id, selection)

  /**
 * Returns information about a suggestion that has the passed id.
 *
 * @param {string} id
 * */
  const getSuggestion = (id) => find(propEq('id', id), suggestions)

  /**
 * Hovers the suggestion on the passed position (index).
 *
 * @param {number} index
 * */
  const hoverSuggestion = (index) => {
    setHoveredIndex(index)
  }

  /**
 * @param {function} directionFn
 * */
  const moveSuggestionSelection = (directionFn) => {
  // Determine boundaries of the suggestions array
    const max = filteredSuggestions.length - 1
    const nextIndex = directionFn(hoveredIndex)

    // Clamps the next hoverIndex between -1 and index of the last suggestion
    // -1 means "no selection"
    const normalizedIndex = clamp(-1, max, nextIndex)

    // Hover the target suggestion
    hoverSuggestion(normalizedIndex)
  }

  /**
 * Filters the available suggestions based on the passed query.
 *
 * @param {string|null} query
 * @param {object[]} [library] - array of objects that the search will run through
 * */
  const filterSuggestions = (query = searchValue, library = suggestions) => {
    if (isEmptyOrNil(query)) {
      setFilteredSuggestions(library)
      return
    }

    const results = getCurrent(fuseInstance).search(query, { keys: filterProps })
    const next = map(prop('item'), results)

    setFilteredSuggestions(next)
    hoverSuggestion(-1)
  }

  /**
 * Focuses the search input.
 * */
  const focusSearch = () => {
    const node = getCurrent(searchInputRef)

    // Sometimes, when user clicks on the dropdown (or any syntetic button)
    // the onclick event is ignored. The reason to that is a strange
    // bug inside the AutosizeInput. For now, we use this
    // this strange way to fix that, but the problem should
    // be investigated and reported to the component provider.
    node.focus() // focus on the input
    node.blur() // blur and reset all syntetic event handlers
    node.focus() // focus again, but this time without messing with the handlers
  }

  /**
 * Blurs the search input.
 * */
  const blurSearch = () => {
    getCurrent(searchInputRef).blur()
  }

  /**
 * Opens the suggestions dropdown.
 * */
  const openDropdown = () => {
    setIsDropdownVisible(true)
    focusSearch()
  }

  /**
   * Closes the suggestions dropdown.
   * */
  const closeDropdown = () => {
    setIsDropdownVisible(false)
    blurSearch()
    hoverSuggestion(-1)
    setFilteredSuggestions([])
  }

  /**
 * Removes passed id from the selection list.
 *
 * @param {string} id
 * */
  const removeSuggestion = (id) => {
    onSelectionChange(reject(equals(id), selection))
  }

  /**
 * Caches the input value and filters the suggestions based on this value.
 *
 * @param {Event} e
 * @summary Handles input event for the search input.
 * @event input
 * */
  const handleSearch = (value) => {
    // Clones the input value to the state
    setSearchValue(value)

    // Filters the suggestions
    filterSuggestions(value)

    if (!isDropdownVisible) {
      // Opens the suggestions window if was not opened yet
      openDropdown()
    }
  }

  /**
 * Toggles targeted suggestion.
 *
 * @param {string} id - id of the targeted suggestion.
 * */
  const handleSelect = (id) => {
    handleSearch('')

    if (multiple) {
    // Toggles the suggestion state
      if (!checkSelection(id)) {
        // Adds if not added yet
        onSelectionChange(append(id, selection))
      } else {
        // Removes if in the values array
        removeSuggestion(id)
      }
      return
    }

    // Close the suggestions list and replace all values with the passed one
    onSelectionChange([ id ])
    setIsDropdownVisible(false)
  }

  /**
 * Clears the values array.
 * */
  const clearSelection = () => {
    onSelectionChange([])
  }

  const isDisabled = disabled || isEmpty(suggestions)

  /**
 * Toggles the visibility of the suggestions dropdown.
 *
 * @param {Event} e
 * @summary Handles click event for the arrow button.
 * @event onclick
 * */
  // eslint-disable-next-line no-unused-vars
  const handleOpenClick = () => {
    if (isDisabled || isLoading) return

    if (!isDropdownVisible) {
      // Bases suggestions on the searchValue
      filterSuggestions()

      // Opens the dropdown
      openDropdown()
      return
    }

    // Closes the dropdown
    closeDropdown()
  }

  /**
 * Performs different actions based on the clicked button.
 * Uses switch-statement to validate and filter input controls.
 *
 * @param {Event} e
 * @summary Handles keydown event for the search input.
 * @event keydown
 * */
  const handleKeydown = (e) => {
    const { keyCode } = e

    switch (keyCode) {
      case KEY_CODES.DOWN_ARROW:
      case KEY_CODES.UP_ARROW: {
        e.preventDefault()

        // Firing the navigation should
        // open the suggestions list
        if (!isDropdownVisible) {
          openDropdown()
        }

        // Since this action may cause opening of the suggestions container
        // it's important to control that the container is not empty
        // solution is to push all available suggestions if the container is empty,
        // since it's an expected behaviour
        filterSuggestions(searchValue || null)

        const directionFn = (equals(keyCode, KEY_CODES.DOWN_ARROW)) ? inc : dec
        moveSuggestionSelection(directionFn)

        break
      }
      case KEY_CODES.ENTER: {
        const selectedItem = filteredSuggestions[hoveredIndex]
        if (selectedItem) handleSelect(selectedItem.id)
        break
      }
      case KEY_CODES.BACKSPACE: {
        const lastId = getLastSelectedId()

        // Skips if there are no suggestions selected
        // or search input is not empty
        if (isNil(lastId) || !isEmpty(searchValue)) break

        removeSuggestion(lastId)
        break
      }
      case KEY_CODES.ESCAPE:
        closeDropdown()
        focusSearch()
        break
      default:
        break
    }
  }

  useEffect(() => {
    fuseInstance.current = new Fuse([], { keys: filterProps })
  }, [])

  useEffect(() => {
    getCurrent(fuseInstance).setCollection(suggestions)
  }, [ suggestions ])

  useEffect(() => {
    filterSuggestions()
  }, [ suggestions ])

  useLayoutEffect(() => {
    // TODO: Optimize. These operations should be done on a virtual node.
    // Current implementation may destroy the DOM tree.

    // Don't fire calculation if width is set by the parent component
    if (!isNil(width)) return

    const parentNode = wrapperRef.current
    const toggleChildren = (doCalculateChildren) => {
      Array.from(parentNode.children).forEach((item) => {
        // eslint-disable-next-line no-param-reassign
        item.style.transform = (doCalculateChildren)
          ? ''
          : 'scale(0)'
      })
    }

    parentNode.style.width = null
    toggleChildren(false)

    if (parentNode.offsetWidth <= 0) {
      parentNode.style.width = '100%'
    }

    const parentWidth = clamp(60, Infinity, parentNode.offsetWidth)

    setOptimalWidth(parentWidth)
    toggleChildren(true)
  })

  useOutsideClick(wrapperRef, closeDropdown)

  const wrapperClasses = cx(
    'mt-select__wrapper',
    {
      'is-multiple': multiple,
      'is-disabled': isDisabled || isLoading,
    },
    className
  )

  const hideSelected = visibleSelectionElements <= 0

  return (
    <div
      { ...otherProps }
      className={ wrapperClasses }
      onClick={ focusSearch }
      style={ { width: optimalWidth } }
      ref={ wrapperRef }
    >
      <div className="mt-select">
        <div className="mt-select__values">
          { (isEmpty(selection) && withIcon) || hideSelected
            ? (
              <span className="mt-select__values-searchicon">
                { isLoading
                  ? <MTLoader />
                  : <MTIcon align={ false } type={ icon } />
                }
              </span>
            ) : (
              <>
                <SelectionLabels
                  selection={ selection }
                  visibleSelectionElements={ visibleSelectionElements }
                  removeSuggestion={ removeSuggestion }
                  getSuggestion={ getSuggestion }
                  searchValue={ searchValue }
                  multiple={ multiple }
                  isDropdownVisible={ isDropdownVisible }
                />
                { selection.length > visibleSelectionElements && (
                  <MTSelectSelectionAdditional
                    { ...{
                      key: 'additional',
                      additionalItemsLabel,
                      selection,
                      visibleSelectionElements,
                    } }
                  />
                ) }
              </>
            )
          }
          <input
            disabled={ isDisabled }
            ref={ searchInputRef }
            value={ searchValue }
            placeholder={ isLoading ? '' : (!isEmpty(selection) && !hideSelected) ? '' : inputPlaceHolder }
            onChange={ compose(handleSearch, path([ 'target', 'value' ])) }
            onClick={ handleOpenClick }
            onKeyDown={ handleKeydown }
          />
        </div>
        {
          (!isEmpty(selection) && !isDisabled && clearable) && (
            <div
              className="mt-select__clear-icon"
              onClick={ clearSelection }
            >
              <MTIcon align={ true } type="close" />
            </div>
          )
        }
        <div
          className="mt-select__open-icon"
          onClick={ handleOpenClick }
        >
          <MTIcon
            type="triangle-down"
            align={ true }
          />
        </div>
      </div>
      <Dropdown
        isVisible={ isDropdownVisible }
        SuggestionTemplate={ SuggestionTemplate || undefined }
        suggestions={ filteredSuggestions }
        hasMore={ hasMore }
        onReachBottom={ onReachBottom }
        width={ optimalWidth }
        checkSelection={ checkSelection }
        hoveredIndex={ hoveredIndex }
        chooseSelection={ handleSelect }
        supportsMultiple={ multiple }
        filteredSuggestions={ filteredSuggestions }
        isDropdownVisible={ isDropdownVisible }
      />
      {
        (isEmpty(suggestions) && !isNil(emptyMessage)) ? (
          <span className="mt-select__empty-message">{ emptyMessage }</span>
        ) : null
      }
    </div>
  )
}

{
  const {
    string,
    number,
    bool,
    arrayOf,
    shape,
    oneOfType,
    func,
  } = PropTypes

  MTSelect.propTypes = {
    initialSearchInput: string,
    inputPlaceHolder: string,
    width: number,
    multiple: bool,
    disabled: bool,
    clearable: bool,
    selection: arrayOf(string),
    suggestions: oneOfType([
      arrayOf(shape({
        id: string,
        label: string,
        disabled: bool,
      })),
      func,
    ]),
    emptyMessage: string,
    filterProps: arrayOf(string),
    visibleSelectionElements: number,
    additionalItemsLabel: string,
    onSelectionChange: func,
    SuggestionTemplate: func,
    withIcon: bool,
    icon: string,
    isLoading: bool,
    hasMore: bool,
    onReachBottom: func,
  }
}

MTSelect.defaultProps = {
  initialSearchInput: '',
  inputPlaceHolder: 'Select...',
  width: null,
  multiple: false,
  disabled: false,
  clearable: true,
  selection: [],
  suggestions: [],
  emptyMessage: null,
  filterProps: [ 'label' ],
  visibleSelectionElements: Infinity,
  additionalItemsLabel: '',
  onSelectionChange: identity,
  SuggestionTemplate: null,
  icon: 'search',
  withIcon: true,
  isLoading: false,
  hasMore: false,
  onReachBottom: () => {},
}

export default MTSelect
