import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useCallback, useContext, useImperativeHandle, useMemo, useRef, useState } from 'react';
import cls from 'clsx';
import { isDef, preventDefault, range } from '../utils';
import { getRect } from '../hooks/use-rect';
import { callInterceptor } from '../utils/interceptor';
import useClickAway from '../hooks/use-click-away';
import useEventListener from '../hooks/use-event-listener';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import { useTouch } from '../hooks';
const SwipeCell = forwardRef((props, instanceRef) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('swipe-cell', prefixCls);
  const opened = useRef(false);
  const lockClick = useRef(false);
  const startOffset = useRef(0);
  const [state, setState] = useState({
    offset: 0,
    dragging: false
  });
  const [actionWidth, setActionWidth] = useState({
    left: 0,
    right: 0
  });
  const root = useRef();

  const getWidthByNode = node => node ? getRect(node).width : 0;

  const leftRef = useCallback(node => {
    if (node !== null) {
      setActionWidth(v => Object.assign(Object.assign({}, v), {
        left: getWidthByNode(node)
      }));
    }
  }, []);
  const rightRef = useCallback(node => {
    if (node !== null) {
      setActionWidth(v => Object.assign(Object.assign({}, v), {
        right: getWidthByNode(node)
      }));
    }
  }, []);
  const touch = useTouch();
  const leftWidth = useMemo(() => isDef(props.leftWidth) ? +props.leftWidth : actionWidth.left, [props.leftWidth, actionWidth.left]);
  const rightWidth = useMemo(() => isDef(props.rightWidth) ? +props.rightWidth : actionWidth.right, [props.rightWidth, actionWidth.right]);

  const open = side => {
    var _a;

    opened.current = true;
    const offset = side === 'left' ? leftWidth : -rightWidth;
    (_a = props.onOpen) === null || _a === void 0 ? void 0 : _a.call(props, {
      name: props.name,
      position: side
    });
    setState(v => Object.assign(Object.assign({}, v), {
      offset
    }));
  };

  const close = position => {
    var _a;

    if (opened.current) {
      opened.current = false;
      (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props, {
        name: props.name,
        position
      });
    }

    setState(v => Object.assign(Object.assign({}, v), {
      offset: 0
    }));
  };

  const toggle = side => {
    const offset = Math.abs(state.offset);
    const THRESHOLD = 0.15;
    const threshold = opened ? 1 - THRESHOLD : THRESHOLD;
    const width = side === 'left' ? leftWidth : rightWidth;

    if (width && offset > width * threshold) {
      open(side);
    } else {
      close(side);
    }
  };

  const onTouchStart = event => {
    if (!props.disabled) {
      startOffset.current = state.offset;
      touch.start(event);
    }
  };

  const onTouchMove = event => {
    if (props.disabled) {
      return;
    }

    touch.move(event);

    if (touch.isHorizontal()) {
      lockClick.current = true;
      const newState = Object.assign(Object.assign({}, state), {
        dragging: true
      });
      const isEdge = !opened || touch.deltaX.current * startOffset.current < 0;

      if (isEdge) {
        preventDefault(event, props.stopPropagation);
      }

      newState.offset = range(touch.deltaX.current + startOffset.current, -rightWidth, leftWidth);
      setState(newState);
    }
  };

  const onTouchEnd = () => {
    if (state.dragging) {
      setState(v => Object.assign(Object.assign({}, v), {
        dragging: false
      }));
      toggle(state.offset > 0 ? 'left' : 'right'); // compatible with desktop scenario

      setTimeout(() => {
        lockClick.current = false;
      }, 0);
    }
  };

  const onClick = (position = 'outside') => {
    var _a;

    (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props, position);

    if (opened.current && !lockClick.current) {
      callInterceptor({
        interceptor: props.beforeClose,
        args: [{
          name: props.name,
          position
        }],
        done: () => close(position)
      });
    }
  };

  const getClickHandler = (position, stop) => event => {
    if (stop) {
      event.stopPropagation();
    }

    onClick(position);
  };

  const renderSideContent = (side, measuredRef) => {
    if (props[`${side}Action`]) {
      return _jsx("div", Object.assign({
        ref: measuredRef,
        className: cls(bem(side)),
        onClick: getClickHandler(side, true)
      }, {
        children: props[`${side}Action`]
      }));
    }

    return null;
  };

  useClickAway(root, () => onClick('outside'), 'touchstart');
  useImperativeHandle(instanceRef, () => ({
    open,
    close: () => close('outside')
  }));
  const wrapperStyle = {
    transform: `translate3d(${state.offset}px, 0, 0)`,
    transitionDuration: state.dragging ? '0s' : '.6s'
  };
  useEventListener('touchmove', onTouchMove, {
    target: root.current,
    depends: [touch.deltaX]
  });
  return _jsx("div", Object.assign({
    ref: root,
    className: cls(bem()),
    onClick: getClickHandler('cell'),
    onTouchStart: onTouchStart,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, {
    children: _jsxs("div", Object.assign({
      className: cls(bem('wrapper')),
      style: wrapperStyle
    }, {
      children: [renderSideContent('left', leftRef), props.children, renderSideContent('right', rightRef)]
    }))
  }));
});
SwipeCell.defaultProps = {
  name: ''
};
export default SwipeCell;