import { useThrottleFn } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';

interface SubContainerProps extends React.HTMLAttributes<HTMLDivElement> {
  children: React.ReactNode;
  inline?: false | true;
}

const paddingTop = 8;

// 下拉子菜单容器
export function SubContainer({ children, inline = false, ...props }: SubContainerProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const [positionUpdated, setPositionUpdated] = useState(false);
  const [position, setPosition] = useState(0); // 只需要保存水平偏移量

  const { run: updatePosition } = useThrottleFn(
    () => {
      // 移动端无需计算
      if (inline) {
        setPosition(0);
        if (!positionUpdated) {
          setPositionUpdated(true);
        }
        return;
      }
      if (!rootRef.current || !contentRef.current) return;
      const anchor = rootRef.current.parentElement; // 以父容器作为参照
      if (!anchor) return;

      const anchorRect = anchor.getBoundingClientRect();
      const contentRect = contentRef.current.getBoundingClientRect();
      const windowWidth = window.innerWidth;
      const padding = 32;

      // 1. 计算相对于父元素的水平居中位置
      let left = (anchorRect.width - contentRect.width) / 2;

      // 2. 检查容器在视口中的绝对位置
      const absoluteLeft = anchorRect.left + left;

      // 3. 调整水平位置确保不超出窗口
      if (absoluteLeft < 0) {
        // 如果超出左边界，向右偏移
        left = left - absoluteLeft + padding;
      } else if (absoluteLeft + contentRect.width > windowWidth) {
        // 如果超出右边界，向左偏移
        left -= absoluteLeft + contentRect.width - windowWidth + padding;
      }

      setPosition(left);
      if (!positionUpdated) {
        setPositionUpdated(true);
      }
    },
    {
      wait: 100,
    }
  );

  // 监听自身大小变化
  useEffect(() => {
    const resizeObserver = new ResizeObserver(() => {
      updatePosition();
    });

    resizeObserver.observe(rootRef.current!);

    return () => resizeObserver.disconnect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 监听 anchor 的大小变化
  useEffect(() => {
    const anchor = rootRef.current?.parentElement;
    let resizeObserver: ResizeObserver | null = null;

    if (anchor) {
      resizeObserver = new ResizeObserver(() => {
        updatePosition();
      });

      resizeObserver.observe(anchor);
    }

    return () => resizeObserver?.disconnect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      updatePosition();
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div
      ref={rootRef}
      className="navmenu-sub__container"
      style={{
        width: '100%',
        paddingTop: `${paddingTop}px`,
        transform: `translateX(${position}px)`,
        overflow: positionUpdated ? 'visible' : 'hidden',
      }}
      {...props}>
      <div
        style={{
          display: inline ? 'block' : 'inline-block',
          boxShadow: inline ? 'none' : '0px 40px 60px rgba(0, 0, 0, 0.08)',
        }}
        ref={contentRef}>
        {children}
      </div>
    </div>
  );
}

export default SubContainer;
