import {
  defineComponent,
  h,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  type PropType,
  type VNode,
  watch,
} from 'vue';
import { Dropdown, Menu, message } from 'ant-design-vue';
import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
import type { IconType } from 'vue-icons-plus/lib';
import {
  LuCopyX,
  LuListX,
  LuMoreHorizontal,
  LuPanelLeftClose,
  LuPanelRightClose,
} from 'vue-icons-plus/lu';
import type { TabView } from '@/types';
import { useState } from '@/hooks';
import { renderRouteIcon } from '@/utils/routeIcon';
import styles from './style.module.less';

const SCROLL_STEP = 240;

type TabKeyHandler = (key: string) => void;
type TabBatchHandler = (key: string) => void;
type TabAllHandler = () => void;

const renderAiIcon = (Icon: IconType, size = 16) => h(Icon, { size });

/**
 * Chrome 风格的页面标签栏组件
 * - 无滚动条，滚轮横向滚动
 * - 溢出时显示左右导航按钮
 */
const PageTabs = defineComponent({
  name: 'PageTabs',
  props: {
    /** 标签列表 */
    tabs: { type: Array as PropType<TabView[]>, required: true },
    /** 当前激活 key */
    activeKey: { type: String, required: true },
    /** 关闭标签 */
    onClose: { type: Function as PropType<TabKeyHandler>, default: undefined },
    /** 关闭当前标签左侧标签 */
    onCloseLeft: { type: Function as PropType<TabBatchHandler>, default: undefined },
    /** 关闭当前标签右侧标签 */
    onCloseRight: { type: Function as PropType<TabBatchHandler>, default: undefined },
    /** 关闭当前标签以外的标签 */
    onCloseOther: { type: Function as PropType<TabBatchHandler>, default: undefined },
    /** 关闭全部标签 */
    onCloseAll: { type: Function as PropType<TabAllHandler>, default: undefined },
    /** 切换标签 */
    onChange: { type: Function as PropType<TabKeyHandler>, default: undefined },
  },
  setup(props) {
    const scrollRef = ref<HTMLElement>();
    const tabItemRefs = ref<Record<string, HTMLElement | undefined>>({});
    const [showNavLeft, setShowNavLeft] = useState(false);
    const [showNavRight, setShowNavRight] = useState(false);

    let resizeObserver: ResizeObserver | null = null;

    const updateScrollState = () => {
      const el = scrollRef.value;
      if (!el) {
        setShowNavLeft(false);
        setShowNavRight(false);
        return;
      }

      const { scrollLeft, scrollWidth, clientWidth } = el;
      const canScroll = scrollWidth - clientWidth > 1;

      setShowNavLeft(canScroll && scrollLeft > 1);
      setShowNavRight(canScroll && scrollLeft + clientWidth < scrollWidth - 1);
    };

    const scrollByStep = (direction: -1 | 1) => {
      const el = scrollRef.value;
      if (!el) return;
      el.scrollBy({ left: direction * SCROLL_STEP, behavior: 'smooth' });
    };

    const handleWheel = (e: WheelEvent) => {
      const el = scrollRef.value;
      if (!el || el.scrollWidth <= el.clientWidth) return;

      const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
      if (delta === 0) return;

      e.preventDefault();
      el.scrollLeft += delta;
      updateScrollState();
    };

    const scrollActiveTabIntoView = () => {
      nextTick(() => {
        tabItemRefs.value[props.activeKey]?.scrollIntoView({
          behavior: 'smooth',
          block: 'nearest',
          inline: 'nearest',
        });
        updateScrollState();
      });
    };

    watch(() => props.activeKey, scrollActiveTabIntoView);
    watch(() => props.tabs.map((t) => t.path).join(','), scrollActiveTabIntoView);

    const setTabItemRef = (path: string, el: Element | null) => {
      if (el) {
        tabItemRefs.value[path] = el as HTMLElement;
        return;
      }

      delete tabItemRefs.value[path];
    };

    const handleClick = (key: string) => {
      if (key !== props.activeKey && props.onChange) {
        props.onChange(key);
      }
    };

    const handleClose = (key: string, e: Event) => {
      e.stopPropagation();
      if (props.tabs.length <= 1) {
        message.warning('至少保留一个标签');
        return;
      }
      if (props.onClose) {
        props.onClose(key);
      }
    };

    const handleBatchClose = (key: string) => {
      if (props.tabs.length <= 1) {
        message.warning('至少保留一个标签');
        return;
      }

      const activeIndex = props.tabs.findIndex((tab) => tab.path === props.activeKey);
      if (activeIndex === -1) return;

      switch (key) {
        case 'left':
          if (activeIndex === 0) {
            message.warning('左侧没有可关闭的标签页');
            return;
          }
          props.onCloseLeft?.(props.activeKey);
          break;
        case 'right':
          if (activeIndex === props.tabs.length - 1) {
            message.warning('右侧没有可关闭的标签页');
            return;
          }
          props.onCloseRight?.(props.activeKey);
          break;
        case 'other':
          props.onCloseOther?.(props.activeKey);
          break;
        case 'all':
          props.onCloseAll?.();
          break;
      }
    };

    onMounted(() => {
      const el = scrollRef.value;
      if (!el) return;

      el.addEventListener('wheel', handleWheel, { passive: false });
      el.addEventListener('scroll', updateScrollState, { passive: true });

      resizeObserver = new ResizeObserver(updateScrollState);
      resizeObserver.observe(el);
      updateScrollState();
    });

    onBeforeUnmount(() => {
      const el = scrollRef.value;
      if (el) {
        el.removeEventListener('wheel', handleWheel);
        el.removeEventListener('scroll', updateScrollState);
      }
      resizeObserver?.disconnect();
      resizeObserver = null;
    });

    const renderTab = (tab: TabView, i: number) => {
      const isActive = tab.path === props.activeKey;
      const showDivider = i !== 0 && !isActive && props.tabs[i - 1]?.path !== props.activeKey;

      return (
        <div
          key={tab.path}
          ref={(el) => setTabItemRef(tab.path, el as Element | null)}
          class={[styles.tabItem, isActive && styles.tabItemActive].filter(Boolean).join(' ')}
          onClick={() => handleClick(tab.path)}
        >
          <div v-show={showDivider} class={styles.divider} />

          <div class={[styles.tabBg, isActive && styles.tabBgActive].filter(Boolean).join(' ')}>
            <div class={styles.tabBgInner} />
            <svg class={styles.tabBgCurveBefore} height="8" width="8">
              <path d="M 0 8 A 8 8 0 0 0 8 0 L 8 8 Z" />
            </svg>
            <svg class={styles.tabBgCurveAfter} height="8" width="8">
              <path d="M 0 0 A 8 8 0 0 0 8 8 L 0 8 Z" />
            </svg>
          </div>

          <div class={styles.tabContent}>
            {tab.icon ? (
              <span class={styles.tabIcon}>{renderRouteIcon(tab.icon, { size: 16 })}</span>
            ) : null}
            <div class={styles.tabTitle}>{tab.title}</div>
            <div class={styles.tabClose} onClick={(e: Event) => handleClose(tab.path, e)}>
              ✕
            </div>
          </div>
        </div>
      );
    };

    const renderBatchMenuItem = (key: string, icon: VNode, label: string) => (
      <Menu.Item key={key}>
        <div class={styles.batchMenuItem}>
          <span class={styles.batchMenuIcon}>{icon}</span>
          <span>{label}</span>
        </div>
      </Menu.Item>
    );

    return () => (
      <div class={styles.pageTabsWrap}>
        {showNavLeft.value && (
          <button
            type="button"
            class={[styles.navBtn, styles.navBtnLeft].join(' ')}
            aria-label="向左滚动标签"
            onClick={() => scrollByStep(-1)}
          >
            <LeftOutlined />
          </button>
        )}

        <div ref={scrollRef} class={styles.pageTabs}>
          {props.tabs.map((tab, i) => renderTab(tab, i))}
        </div>

        {showNavRight.value && (
          <button
            type="button"
            class={[styles.navBtn, styles.navBtnRight].join(' ')}
            aria-label="向右滚动标签"
            onClick={() => scrollByStep(1)}
          >
            <RightOutlined />
          </button>
        )}

        <Dropdown trigger={['click']} placement="bottomRight">
          {{
            default: () => (
              <button type="button" class={styles.batchBtn} aria-label="标签页操作菜单">
                {renderAiIcon(LuMoreHorizontal)}
              </button>
            ),
            overlay: () => (
              <Menu onClick={({ key }) => handleBatchClose(String(key))}>
                {renderBatchMenuItem('left', renderAiIcon(LuPanelLeftClose), '关闭左侧标签页')}
                {renderBatchMenuItem('right', renderAiIcon(LuPanelRightClose), '关闭右侧标签页')}
                {renderBatchMenuItem('other', renderAiIcon(LuCopyX), '关闭其它标签页')}
                {renderBatchMenuItem('all', renderAiIcon(LuListX), '关闭全部标签页')}
              </Menu>
            ),
          }}
        </Dropdown>
      </div>
    );
  },
});

export default PageTabs;
