import type { EmptyProps } from 'antd';
import { Empty } from 'antd';
import type { ReactNode } from 'react';
import React, { useEffect, useRef, useState } from 'react';

export interface AutoEmptyProps extends EmptyProps {
  /**
   * @description 显示内容
   */
  children?: React.ReactNode;
  noEmptyRender?: () => ReactNode;
}

const AutoEmpty = (props: AutoEmptyProps) => {
  const { children, noEmptyRender, ...emptyProps } = props;
  const [empty, setEmpty] = useState<boolean | undefined>(undefined);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const observerRef = useRef<MutationObserver>();

  useEffect(() => {
    if (!wrapperRef.current) return;

    setEmpty(!wrapperRef.current?.hasChildNodes());
    observerRef.current = new MutationObserver(() => {
      const hasChildren = wrapperRef.current?.hasChildNodes();
      setEmpty(!hasChildren);
    });

    observerRef.current.observe(wrapperRef.current, {
      childList: true, // 监控直接子节点
      subtree: true, // 监控所有后代
      characterData: true, // 监控文本变化
    });

    return () => observerRef.current?.disconnect();
  }, []);

  return (
    <>
      <div ref={wrapperRef} style={{ display: 'contents' }}>
        {empty === false && noEmptyRender?.()}
        {children}
      </div>
      {empty && <Empty {...emptyProps} />}
    </>
  );
};

export default AutoEmpty;
