import { Box } from '@mui/material';
import { useState, ReactNode, useEffect, createContext, useContext, useMemo, useRef, useCallback } from 'react';

const ConditionalSectionContext = createContext<{
  hideRender: (hide?: boolean) => void;
} | null>(null);

// 导出hook供子组件使用
export const useConditionalSection = () => {
  const context = useContext(ConditionalSectionContext);
  return context;
};

interface ConditionalSectionProps {
  skeleton: boolean;
  children: ReactNode;
  skeletonComponent?: ReactNode;
  onStateChange?: (state: 'hidden' | 'visible' | 'none') => void;
}

/**
 * 条件渲染组件 - 完全防闪现版本
 *
 * 彻底解决闪现问题的方案：
 * 1. skeleton=true 时显示骨架屏组件
 * 2. skeleton=false 时完全隐藏(display: none)渲染子组件，让其执行逻辑
 * 3. 等待子组件执行完毕，如果没有调用hideRender则显示
 * 4. 整个过程用户看不到任何闪现
 *
 * 使用方式：
 * - 在任意深度的子组件中调用 useConditionalSection()?.hideRender()
 */
export default function ConditionalSection({
  skeleton,
  children,
  skeletonComponent = null,
  onStateChange = () => {},
}: ConditionalSectionProps) {
  const [renderState, setRenderState] = useState<'hidden' | 'visible' | 'none'>('hidden');
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    onStateChange(renderState);
  }, [renderState]);

  const handleHideRender = useCallback((hide: boolean = true) => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    setRenderState(hide ? 'none' : 'visible');
  }, []);

  const contextValue = useMemo(() => ({ hideRender: handleHideRender }), [handleHideRender]);

  useEffect(() => {
    if (!skeleton) {
      timerRef.current = setTimeout(() => {
        setRenderState('visible');
        timerRef.current = null;
      }, 3000);
    }

    // 清理定时器
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [skeleton]);

  if (skeleton) {
    return skeletonComponent;
  }

  if (renderState === 'none') {
    return null;
  }

  return (
    <ConditionalSectionContext.Provider value={contextValue}>
      <Box
        sx={{
          position: renderState === 'hidden' ? 'absolute' : 'static',
          left: renderState === 'hidden' ? '-9999px' : 'auto',
          top: renderState === 'hidden' ? '-9999px' : 'auto',
          visibility: renderState === 'hidden' ? 'hidden' : 'visible',
          width: renderState === 'hidden' ? '0' : 'auto',
          height: renderState === 'hidden' ? '0' : 'auto',
          overflow: 'hidden',
        }}>
        {children}
      </Box>
    </ConditionalSectionContext.Provider>
  );
}
