import React, { useMemo, useRef, useEffect, forwardRef, useImperativeHandle, useState, useContext } from 'react';
import clsx from 'clsx';
import useRefs from '../hooks/use-refs';
import useScrollParent from '../hooks/use-scroll-parent';
import useWindowSize from '../hooks/use-window-size';
import Sticky from '../sticky';
import TabsTitle from './TabsTitle';
import TabsContent from './TabsContent';
import TabsContext from './TabsContext';
import { addUnit, parseChildList, isHidden, isDef, unitToPx, scrollLeftTo, getElementTop, getVisibleHeight, scrollTopTo, getVisibleTop, setRootScrollTop } from '../utils';
import { callInterceptor } from '../utils/interceptor';
import { BORDER_TOP_BOTTOM } from '../utils/constant';
import { useSetState, useUpdateEffect } from '../hooks';
import useEventListener from '../hooks/use-event-listener';
import { isReachBottom } from './utils';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import PopupContext from '../popup/PopupContext';
var Tabs = /*#__PURE__*/forwardRef(function (props, ref) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var popupContext = useContext(PopupContext);

  var _createNamespace = createNamespace('tabs', prefixCls),
      bem = _createNamespace[0];

  var children = props.children,
      color = props.color,
      align = props.align,
      background = props.background;
  var root = useRef(null);
  var swiperRef = useRef(null);

  var _useState = useState(null),
      wrapRef = _useState[0],
      setWrapRef = _useState[1];

  var initChange = useRef(false);
  var lockScroll = useRef(false);
  var stickyFixed = useRef(false);
  var navRef = useRef(null);
  var scroller = useScrollParent(root);
  var windowSize = useWindowSize();

  var _useRefs = useRefs(),
      titleRefs = _useRefs[0],
      setTitleRefs = _useRefs[1];

  var _useRefs2 = useRefs(),
      contentRefs = _useRefs2[0],
      setContentRefs = _useRefs2[1];

  var tabHeight = useMemo(function () {
    if (!wrapRef) return 0;
    return getVisibleHeight(wrapRef);
  }, [wrapRef]);
  var tabHeightRef = useRef(tabHeight);
  tabHeightRef.current = tabHeight;

  var _useSetState = useSetState({
    inited: false,
    position: '',
    currentIndex: -1,
    lineStyle: {
      backgroundColor: props.color
    }
  }),
      state = _useSetState[0],
      setState = _useSetState[1];

  var childrenList = useMemo(function () {
    return parseChildList(props.children);
  }, [props.children]); // whether the nav is scrollable

  var scrollable = useMemo(function () {
    return childrenList.length > props.swipeThreshold || !props.ellipsis;
  }, [childrenList.length, props.swipeThreshold, props.ellipsis]);
  var navStyle = useMemo(function () {
    return {
      borderColor: color,
      background: background
    };
  }, [color, background]);

  var getTabName = function getTabName(tab, index) {
    var _tab$name;

    return (_tab$name = tab == null ? void 0 : tab.name) != null ? _tab$name : index;
  };

  var currentName = useMemo(function () {
    var activeTab = childrenList[state.currentIndex];
    return activeTab ? getTabName(activeTab, state.currentIndex) : 0;
  }, [childrenList, state.currentIndex]);
  var offsetTopPx = useMemo(function () {
    return unitToPx(props.offsetTop);
  }, [props.offsetTop]); // scroll active tab into view

  var scrollIntoView = function scrollIntoView(immediate) {
    var nav = navRef.current;

    if (!scrollable || !nav || !titleRefs || !titleRefs[state.currentIndex]) {
      return;
    }

    var title = titleRefs[state.currentIndex];
    var to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2;
    scrollLeftTo(nav, to, immediate ? 0 : +props.duration);
  };

  var setLine = function setLine(immediate) {
    var shouldAnimate = state.inited;
    if (immediate) shouldAnimate = false;
    var titles = titleRefs;
    var hidden = isHidden(root.current);

    if (!titles || !titles[state.currentIndex] || props.type !== 'line' || hidden) {
      return;
    }

    var title = titles[state.currentIndex];
    var lineWidth = props.lineWidth,
        lineHeight = props.lineHeight;
    var left = title.offsetLeft + title.offsetWidth / 2;
    var lineStyle = {
      width: addUnit(lineWidth),
      backgroundColor: props.color,
      transform: "translateX(" + left + "px) translateX(-50%)"
    };

    if (shouldAnimate) {
      lineStyle.transitionDuration = props.duration + "ms";
    }

    if (isDef(lineHeight)) {
      var height = addUnit(lineHeight);
      lineStyle.height = height;
      lineStyle.borderRadius = height;
    }

    setState({
      lineStyle: lineStyle
    });
  };

  var findAvailableTab = function findAvailableTab(index) {
    var diff = index < state.currentIndex ? -1 : 1;

    while (index >= 0 && index < childrenList.length) {
      if (!childrenList[index].disabled) {
        return index;
      }

      index += diff;
    }

    return null;
  };

  var setCurrentIndex = function setCurrentIndex(currentIndex) {
    var newIndex = findAvailableTab(currentIndex);

    if (!isDef(newIndex)) {
      return;
    }

    var newTab = childrenList[newIndex];
    var newName = getTabName(newTab, newIndex);
    var shouldEmitChange = state.currentIndex !== null;
    setState({
      currentIndex: newIndex
    });

    if (!initChange.current) {
      initChange.current = true;
      return;
    }

    if (initChange.current) {
      if (shouldEmitChange) {
        props.onChange == null ? void 0 : props.onChange(newName, newTab.title);
      }
    }
  }; // correct the index of active tab


  var setCurrentIndexByName = function setCurrentIndexByName(name) {
    var currentIndex = childrenList.findIndex(function (tab, index) {
      return getTabName(tab, index) === name;
    });
    setCurrentIndex(currentIndex < 0 ? 0 : currentIndex);
  };

  var scrollToCurrentContent = function scrollToCurrentContent(immediate, current) {
    if (props.scrollspy) {
      var target = contentRefs[current != null ? current : state.currentIndex];

      if (target && scroller) {
        var to = getElementTop(target, scroller) - (offsetTopPx + tabHeightRef.current);
        lockScroll.current = true;
        scrollTopTo(scroller, to, immediate ? 0 : +props.duration, function () {
          lockScroll.current = false;
        });
      }
    }
  };

  var onClickTab = function onClickTab(item, index, event) {
    var title = item.title,
        _item$disabled = item.disabled,
        disabled = _item$disabled === void 0 ? false : _item$disabled;
    var name = getTabName(item, index);
    props.onClickTab == null ? void 0 : props.onClickTab({
      name: name,
      title: title,
      event: event,
      disabled: disabled
    });
    if (disabled) return;
    callInterceptor({
      interceptor: props.beforeChange,
      args: [name],
      done: function done() {
        if (index !== state.currentIndex) {
          setCurrentIndex(index);
          scrollToCurrentContent(false, index);
        }
      }
    });
  };

  var scrollTo = function scrollTo(name) {
    setCurrentIndexByName(name);
    scrollToCurrentContent(true);
  };

  var getCurrentIndexOnScroll = function getCurrentIndexOnScroll() {
    var scrollOffset = offsetTopPx + tabHeightRef.current; // eslint-disable-next-line no-plusplus

    for (var index = 0; index < contentRefs.length; index++) {
      var $el = contentRefs[index];
      var top = getVisibleTop($el);

      if (top > scrollOffset) {
        return index === 0 ? 0 : index - 1;
      }
    }

    return titleRefs.length - 1;
  };

  var onScroll = function onScroll() {
    if (props.scrollspy && !lockScroll.current) {
      var index = getCurrentIndexOnScroll();

      if (typeof props.scrollspy === 'object') {
        if (props.scrollspy.autoFocusLast && isReachBottom(props.scrollspy.reachBottomThreshold)) {
          index = titleRefs.length - 1;
        }
      }

      if (index !== state.currentIndex) {
        setCurrentIndex(index);
      }
    }
  };

  var onStickyScroll = function onStickyScroll(params) {
    stickyFixed.current = params.isFixed;
    props.onScroll == null ? void 0 : props.onScroll(params);
  };

  var renderNav = function renderNav() {
    return childrenList.map(function (item, index) {
      return /*#__PURE__*/React.createElement(TabsTitle, {
        ref: setTitleRefs(index),
        key: item.key,
        dot: item.dot,
        type: props.type,
        badge: item.badge,
        title: item.title,
        color: props.color,
        style: item.titleStyle,
        className: item.titleClass,
        isActive: index === state.currentIndex,
        disabled: item.disabled,
        scrollable: scrollable,
        renderTitle: item.renderTitle,
        activeColor: props.titleActiveColor,
        inactiveColor: props.titleInactiveColor,
        showZeroBadge: item.showZeroBadge,
        onClick: function onClick(event) {
          onClickTab(item, index, event);
        }
      });
    });
  };

  var renderHeader = function renderHeader() {
    var _ref;

    var type = props.type,
        border = props.border;
    return /*#__PURE__*/React.createElement("div", {
      ref: setWrapRef,
      className: clsx([bem('wrap', {
        scrollable: scrollable
      }), (_ref = {}, _ref[BORDER_TOP_BOTTOM] = type === 'line' && border, _ref)])
    }, /*#__PURE__*/React.createElement("div", {
      ref: navRef,
      role: "tablist",
      className: clsx(bem('nav', [type, {
        complete: scrollable,
        start: align === 'start'
      }])),
      style: navStyle
    }, props.navRight, renderNav(), type === 'line' && /*#__PURE__*/React.createElement("div", {
      className: clsx(bem('line')),
      style: state.lineStyle
    }), props.navRight));
  };

  useUpdateEffect(function () {
    setLine();
  }, [props.color, windowSize.width]);
  useUpdateEffect(function () {
    if (props.active !== currentName) {
      setCurrentIndexByName(props.active);
    }
  }, [props.active]);
  useUpdateEffect(function () {
    if (state.inited) {
      setCurrentIndexByName(props.active || currentName);
      setLine();
      scrollIntoView(true);
    }
  }, [React.Children.count(children)]);
  useUpdateEffect(function () {
    scrollIntoView();
    setLine(); // scroll to correct position

    if (stickyFixed.current && props.stickyInitScrollbar && !props.scrollspy) {
      setRootScrollTop(Math.ceil(getElementTop(root.current) - offsetTopPx));
    }
  }, [state.currentIndex]);

  var init = function init() {
    setCurrentIndexByName(props.active);
    scrollIntoView(true);
    setState({
      inited: true
    });
  };

  useEffect(function () {
    init();
  }, []);
  useUpdateEffect(function () {
    if (popupContext.visible) {
      setLine();
    }
  }, [popupContext.visible]);
  useEventListener('scroll', onScroll, {
    target: scroller,
    depends: [state.currentIndex]
  });
  useImperativeHandle(ref, function () {
    var _swiperRef$current, _swiperRef$current2;

    return {
      resize: setLine,
      scrollTo: scrollTo,
      swiper: swiperRef.current ? {
        enable: (_swiperRef$current = swiperRef.current) == null ? void 0 : _swiperRef$current.enable,
        disable: (_swiperRef$current2 = swiperRef.current) == null ? void 0 : _swiperRef$current2.disable
      } : undefined
    };
  });

  var onStickyChange = function onStickyChange() {
    setLine(true);
  };

  return /*#__PURE__*/React.createElement(TabsContext.Provider, {
    value: {
      props: props,
      currentName: currentName,
      scrollIntoView: scrollIntoView,
      setLine: setLine
    }
  }, /*#__PURE__*/React.createElement("div", {
    ref: root,
    className: clsx(props.className, bem([props.type]))
  }, props.sticky ? /*#__PURE__*/React.createElement(Sticky, {
    container: root,
    offsetTop: offsetTopPx,
    onChange: onStickyChange,
    onScroll: onStickyScroll
  }, renderHeader(), props.navBottom) : /*#__PURE__*/React.createElement(React.Fragment, null, renderHeader(), props.navBottom), /*#__PURE__*/React.createElement(TabsContent, {
    swiperRef: swiperRef,
    count: childrenList.length,
    inited: state.inited,
    animated: props.animated,
    duration: props.duration,
    swipeable: props.swipeable,
    lazyRender: props.lazyRender,
    currentIndex: state.currentIndex,
    onChange: setCurrentIndex
  }, React.Children.toArray(children).filter(Boolean).map(function (node, index) {
    return /*#__PURE__*/React.cloneElement(node, {
      index: index,
      ref: setContentRefs(index)
    });
  }))));
});
Tabs.defaultProps = {
  type: 'line',
  duration: 300,
  swipeThreshold: 5,
  offsetTop: 0,
  ellipsis: true,
  lazyRender: true,
  stickyInitScrollbar: true,
  active: 0,
  align: 'center'
};
export default Tabs;