import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
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';
const Tabs = forwardRef((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const popupContext = useContext(PopupContext);
  const [bem] = createNamespace('tabs', prefixCls);
  const {
    children,
    color,
    align,
    background
  } = props;
  const root = useRef(null);
  const swiperRef = useRef(null);
  const [wrapRef, setWrapRef] = useState(null);
  const initChange = useRef(false);
  const lockScroll = useRef(false);
  const stickyFixed = useRef(false);
  const navRef = useRef(null);
  const scroller = useScrollParent(root);
  const windowSize = useWindowSize();
  const [titleRefs, setTitleRefs] = useRefs();
  const [contentRefs, setContentRefs] = useRefs();
  const tabHeight = useMemo(() => {
    if (!wrapRef) return 0;
    return getVisibleHeight(wrapRef);
  }, [wrapRef]);
  const tabHeightRef = useRef(tabHeight);
  tabHeightRef.current = tabHeight;
  const [state, setState] = useSetState({
    inited: false,
    position: '',
    currentIndex: -1,
    lineStyle: {
      backgroundColor: props.color
    }
  });
  const childrenList = useMemo(() => parseChildList(props.children), [props.children]); // whether the nav is scrollable

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

  const getTabName = (tab, index) => {
    var _a;

    return (_a = tab === null || tab === void 0 ? void 0 : tab.name) !== null && _a !== void 0 ? _a : index;
  };

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

  const scrollIntoView = immediate => {
    const nav = navRef.current;

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

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

  const setLine = immediate => {
    let shouldAnimate = state.inited;
    if (immediate) shouldAnimate = false;
    const titles = titleRefs;
    const hidden = isHidden(root.current);

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

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

    if (shouldAnimate) {
      lineStyle.transitionDuration = `${props.duration}ms`;
    }

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

    setState({
      lineStyle
    });
  };

  const findAvailableTab = (index, initial) => {
    var _a;

    const diff = index < state.currentIndex ? -1 : 1;

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

      if (!((_a = childrenList[index]) === null || _a === void 0 ? void 0 : _a.disabled)) {
        return index;
      }

      index += diff;
    }

    return null;
  };

  const setCurrentIndex = (currentIndex, initial) => {
    var _a;

    const newIndex = findAvailableTab(currentIndex, initial);

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

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

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

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


  const setCurrentIndexByName = (name, initial) => {
    const currentIndex = childrenList.findIndex((tab, index) => getTabName(tab, index) === name);
    setCurrentIndex(currentIndex < 0 ? 0 : currentIndex, initial);
  };

  const scrollToCurrentContent = (immediate, current) => {
    if (props.scrollspy) {
      const target = contentRefs[current !== null && current !== void 0 ? current : state.currentIndex];

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

  const onClickTab = (item, index, event) => {
    var _a;

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

  const scrollTo = name => {
    setCurrentIndexByName(name);
    scrollToCurrentContent(true);
  };

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

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

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

    return titleRefs.length - 1;
  };

  const onScroll = () => {
    if (props.scrollspy && !lockScroll.current) {
      let 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);
      }
    }
  };

  const onStickyScroll = params => {
    var _a;

    stickyFixed.current = params.isFixed;
    (_a = props.onScroll) === null || _a === void 0 ? void 0 : _a.call(props, params);
  };

  const renderNav = () => {
    return childrenList.map((item, index) => {
      return _jsx(TabsTitle, {
        ref: setTitleRefs(index),
        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: event => {
          onClickTab(item, index, event);
        }
      }, item.key);
    });
  };

  const renderHeader = () => {
    const {
      type,
      border
    } = props;
    return _jsx("div", Object.assign({
      ref: setWrapRef,
      className: clsx([bem('wrap', {
        scrollable
      }), {
        [BORDER_TOP_BOTTOM]: type === 'line' && border
      }])
    }, {
      children: _jsxs("div", Object.assign({
        ref: navRef,
        role: "tablist",
        className: clsx(bem('nav', [type, {
          complete: scrollable,
          start: align === 'start'
        }])),
        style: navStyle
      }, {
        children: [props.navRight, renderNav(), type === 'line' && _jsx("div", {
          className: clsx(bem('line')),
          style: state.lineStyle
        }), props.navRight]
      }))
    }));
  };

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

    if (stickyFixed.current && props.stickyInitScrollbar && !props.scrollspy) {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      setRootScrollTop(Math.ceil(getElementTop(root.current) - offsetTopPx));
    }
  }, [state.currentIndex]);

  const initialRun = () => {
    setCurrentIndexByName(props.active, true);
    scrollIntoView(true);
    setState({
      inited: true
    });
  };

  useEffect(() => {
    initialRun(); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useUpdateEffect(() => {
    if (popupContext.visible) {
      setLine();
    }
  }, [popupContext.visible]);
  useEventListener('scroll', onScroll, {
    target: scroller,
    depends: [state.currentIndex]
  });
  useImperativeHandle(ref, () => {
    var _a, _b;

    return {
      resize: setLine,
      scrollTo,
      swiper: swiperRef.current ? {
        enable: (_a = swiperRef.current) === null || _a === void 0 ? void 0 : _a.enable,
        disable: (_b = swiperRef.current) === null || _b === void 0 ? void 0 : _b.disable
      } : undefined
    };
  });

  const onStickyChange = () => {
    setLine(true);
  };

  return _jsx(TabsContext.Provider, Object.assign({
    value: {
      props,
      currentName,
      scrollIntoView,
      setLine
    }
  }, {
    children: _jsxs("div", Object.assign({
      ref: root,
      className: clsx(props.className, bem([props.type]))
    }, {
      children: [props.sticky ? _jsxs(Sticky, Object.assign({
        container: root,
        offsetTop: offsetTopPx,
        onChange: onStickyChange,
        onScroll: onStickyScroll
      }, {
        children: [renderHeader(), props.navBottom]
      })) : _jsxs(_Fragment, {
        children: [renderHeader(), props.navBottom]
      }), _jsx(TabsContent, Object.assign({
        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
      }, {
        children: React.Children.toArray(children).filter(Boolean).map((node, index) => React.cloneElement(node, {
          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;