/* eslint-disable @typescript-eslint/naming-convention */
import React, { useEffect, useMemo, useRef, useImperativeHandle, useCallback, forwardRef, useContext } from 'react';
import clsx from 'clsx';
import useTouch from '../hooks/use-touch';
import { isObject, range } from '../utils';
import { deepClone } from '../utils/deep-clone';
import { useSetState, useUpdateEffect } from '../hooks';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import { raf } from '../utils/raf';
var DEFAULT_DURATION = 200; // 惯性滑动思路:
// 在手指离开屏幕时，如果和上一次 move 时的间隔小于 `MOMENTUM_LIMIT_TIME` 且 move
// 距离大于 `MOMENTUM_LIMIT_DISTANCE` 时，执行惯性滑动

var MOMENTUM_LIMIT_TIME = 300;
var MOMENTUM_LIMIT_DISTANCE = 15;

function getElementTranslateY(element) {
  var style = window.getComputedStyle(element);
  var transform = style.transform || style.webkitTransform;
  var translateY = transform.slice(7, transform.length - 1).split(', ')[5];
  return Number(translateY);
}

function isOptionDisabled(option) {
  return isObject(option) && option.disabled;
}

var PickerColumn = /*#__PURE__*/forwardRef(function (props, ref) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('picker-column', prefixCls),
      bem = _createNamespace[0];

  var itemHeight = props.itemHeight,
      visibleItemCount = props.visibleItemCount,
      defaultIndex = props.defaultIndex,
      initialOptions = props.initialOptions;
  var root = useRef(null);
  var wrapper = useRef(null);
  var moving = useRef(false);
  var startOffset = useRef(0);
  var transitionEndTrigger = useRef(null);
  var touchStartTime = useRef(0);
  var momentumOffset = useRef(0);

  var _useSetState = useSetState({
    index: defaultIndex,
    offset: 0,
    duration: 0,
    options: deepClone(initialOptions)
  }),
      state = _useSetState[0],
      updateState = _useSetState[1];

  var touch = useTouch();
  var count = useMemo(function () {
    return state.options.length;
  }, [state.options.length]);
  var baseOffset = useMemo(function () {
    // 默认转入第一个选项的位置
    return itemHeight * (+visibleItemCount - 1) / 2;
  }, [itemHeight, visibleItemCount]);

  var adjustIndex = function adjustIndex(index) {
    index = range(index, 0, count);

    for (var i = index; i < count; i += 1) {
      if (!isOptionDisabled(state.options[i])) return i;
    }

    for (var _i = index - 1; _i >= 0; _i -= 1) {
      if (!isOptionDisabled(state.options[_i])) return _i;
    }

    return null;
  };

  var setIndex = function setIndex(index, emitChange) {
    index = adjustIndex(index) || 0;
    var offset = -index * props.itemHeight;

    var trigger = function trigger() {
      if (index !== state.index) {
        updateState({
          index: index
        });

        if (emitChange && props.onChange) {
          raf(function () {
            props.onChange(index);
          });
        }
      }
    }; // trigger the change event after transitionend when moving


    if (moving.current && offset !== state.offset) {
      transitionEndTrigger.current = trigger;
    } else {
      trigger();
    }

    updateState({
      offset: offset
    });
  };

  var setOptions = function setOptions(options) {
    if (JSON.stringify(options) !== JSON.stringify(state.options)) {
      updateState({
        options: deepClone(options)
      });
      setIndex(props.defaultIndex);
    }
  };

  var onClickItem = function onClickItem(index) {
    if (moving.current || props.readonly) {
      return;
    }

    transitionEndTrigger.current = null;
    updateState({
      duration: DEFAULT_DURATION
    });
    setIndex(index, true);
  };

  var getOptionText = function getOptionText(option) {
    if (isObject(option) && props.textKey in option) {
      return option[props.textKey];
    }

    return option;
  };

  var getIndexByOffset = function getIndexByOffset(offset) {
    return range(Math.round(-offset / props.itemHeight), 0, count - 1);
  };

  var momentum = function momentum(distance, _duration) {
    var speed = Math.abs(distance / _duration);
    distance = state.offset + speed / 0.003 * (distance < 0 ? -1 : 1);
    var index = getIndexByOffset(distance);
    updateState({
      duration: +props.swipeDuration
    });
    setIndex(index, true);
  };

  var stopMomentum = function stopMomentum() {
    moving.current = false;
    updateState({
      duration: 0
    });

    if (transitionEndTrigger.current) {
      transitionEndTrigger.current();
      transitionEndTrigger.current = null;
    }
  };

  var onTouchStart = function onTouchStart(event) {
    if (props.readonly) {
      return;
    }

    touch.start(event);
    var offset = state.offset;

    if (moving.current) {
      var translateY = getElementTranslateY(wrapper.current);
      offset = Math.min(0, translateY - baseOffset);
      startOffset.current = offset;
    } else {
      startOffset.current = offset;
    }

    updateState({
      duration: 0,
      offset: offset
    });
    touchStartTime.current = Date.now();
    momentumOffset.current = startOffset.current;
    transitionEndTrigger.current = null;
  };

  var onTouchMove = function onTouchMove(event) {
    if (props.readonly) {
      return;
    }

    touch.move(event);

    if (touch.isVertical()) {
      moving.current = true;
    }

    var offset = range(startOffset.current + touch.deltaY, -(count * props.itemHeight), props.itemHeight);
    updateState({
      offset: offset
    });
    var now = Date.now();

    if (now - touchStartTime.current > MOMENTUM_LIMIT_TIME) {
      touchStartTime.current = now;
      momentumOffset.current = offset;
    }
  };

  var onTouchEnd = function onTouchEnd() {
    if (props.readonly) {
      return;
    }

    var distance = state.offset - momentumOffset.current;
    var duration = Date.now() - touchStartTime.current;
    var allowMomentum = duration < MOMENTUM_LIMIT_TIME && Math.abs(distance) > MOMENTUM_LIMIT_DISTANCE;

    if (allowMomentum) {
      momentum(distance, duration);
      return;
    }

    var index = getIndexByOffset(state.offset);
    updateState({
      duration: DEFAULT_DURATION
    });
    setIndex(index, true); // compatible with desktop scenario
    // use setTimeout to skip the click event triggered after touchstart

    setTimeout(function () {
      moving.current = false;
    }, 0);
  };

  var renderOptions = function renderOptions() {
    var optionStyle = {
      height: props.itemHeight + "px"
    };
    return state.options.map(function (option, index) {
      var text = getOptionText(option);
      var disabled = isOptionDisabled(option);
      var data = {
        role: 'button',
        key: index,
        style: optionStyle,
        tabIndex: disabled ? -1 : 0,
        className: clsx(bem('item', {
          disabled: disabled,
          selected: index === state.index
        })),
        onClick: function onClick() {
          onClickItem(index);
        }
      };
      var childData = {
        className: 'rv-ellipsis',
        children: text
      };
      return /*#__PURE__*/React.createElement("li", data, props.optionRender ? props.optionRender(option) : /*#__PURE__*/React.createElement("div", childData));
    });
  };

  var setValue = function setValue(value) {
    var options = state.options;

    for (var i = 0; i < options.length; i += 1) {
      if (getOptionText(options[i]) === value) {
        return setIndex(i);
      }
    }

    return null;
  };

  var getValue = useCallback(function () {
    return state.options[state.index];
  }, [state.index, state.options]);
  useEffect(function () {
    setIndex(defaultIndex);
  }, [defaultIndex]);
  useUpdateEffect(function () {
    setOptions(initialOptions);
  }, [initialOptions]);
  useImperativeHandle(ref, function () {
    return {
      state: state,
      setIndex: setIndex,
      getValue: getValue,
      setValue: setValue,
      setOptions: setOptions,
      stopMomentum: stopMomentum
    };
  });
  return /*#__PURE__*/React.createElement("div", {
    ref: root,
    className: clsx(bem(), props.className),
    onTouchStart: onTouchStart,
    onTouchMove: onTouchMove,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, /*#__PURE__*/React.createElement("ul", {
    ref: wrapper,
    style: {
      transform: "translate3d(0, " + (state.offset + baseOffset) + "px, 0)",
      transitionDuration: state.duration + "ms",
      transitionProperty: state.duration ? 'all' : 'none'
    },
    className: clsx(bem('wrapper')),
    onTransitionEnd: stopMomentum
  }, renderOptions()));
});
PickerColumn.defaultProps = {
  initialOptions: [],
  defaultIndex: 0
};
export default PickerColumn;