// FE-EXP002: 前端性能优化
import {
  useState,
  useEffect,
  useRef,
  Spin,
  Alert,
  Card,
  Row,
  Col,
  LoadingOutlined,
  CheckCircleOutlined,
  AlertOutlined,
  DatabaseOutlined,
  ReactNode,
  FC,
} from '@/imports';

interface PerformanceMetrics {
  renderTime: number;
  memoryUsage?: number;
  componentCount?: number;
}

interface PerformanceMonitorProps {
  children: ReactNode;
  threshold?: number;
  onPerformanceIssue?: (metrics: PerformanceMetrics) => void;
}

// 性能监控组件
export const PerformanceMonitor: FC<PerformanceMonitorProps> = ({ children, threshold = 100, onPerformanceIssue }) => {
  const [metrics, setMetrics] = useState<PerformanceMetrics | null>(null);
  const startTime = useRef<number>(0);

  useEffect(() => {
    startTime.current = performance.now();
    
    return () => {
      const renderTime = performance.now() - startTime.current;
      if (renderTime > threshold) {
        const newMetrics: PerformanceMetrics = {
          renderTime,
          memoryUsage: (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory?.usedJSHeapSize,
        };
        setMetrics(newMetrics);
        onPerformanceIssue?.(newMetrics);
      }
    };
  }, [threshold, onPerformanceIssue]);

  if (metrics && metrics.renderTime > threshold) {
    return (
      <Alert
        type="warning"
        message="Performance Warning"
        description={`Render time: ${metrics.renderTime.toFixed(2)}ms exceeds threshold of ${threshold}ms`}
        showIcon
      />
    );
  }

  return <>{children}</>;
};

interface LazyLoadProps {
  children: ReactNode;
  threshold?: number;
  placeholder?: ReactNode;
}

// 懒加载组件
export const LazyLoad: FC<LazyLoadProps> = ({
  children,
  threshold = 100,
  placeholder = <Spin size="small" />,
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );
    
    if (ref.current) {
      observer.observe(ref.current);
    }
    
    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [threshold]);
  
  return (
    <div ref={ref}>
      {isVisible ? children : placeholder}
    </div>
  );
};

interface DebouncedInputProps {
  value: string;
  onChange: (value: string) => void;
  delay?: number;
  placeholder?: string;
}

// 防抖组件
export const DebouncedInput: FC<DebouncedInputProps> = ({ value, onChange, delay = 300, placeholder }) => {
  const [localValue, setLocalValue] = useState(value);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    setLocalValue(value);
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    setLocalValue(newValue);

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      onChange(newValue);
    }, delay);
  };

  return (
    <input
      value={localValue}
      onChange={handleChange}
      placeholder={placeholder}
      style={{ width: '100%', padding: '8px' }}
    />
  );
};

interface CachedComponentProps {
  children: ReactNode;
  cacheKey: string;
  cacheTime?: number;
}

// 缓存组件
export const CachedComponent: FC<CachedComponentProps> = ({
  children,
  cacheKey,
  cacheTime = 5 * 60 * 1000,
}) => {
  const [cachedContent, setCachedContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadCachedContent = () => {
      try {
        const cached = localStorage.getItem(cacheKey);
        const meta = JSON.parse(localStorage.getItem(`${cacheKey}_meta`) || '{}');
        
        if (cached && meta.timestamp) {
          const now = Date.now();
          if (now - meta.timestamp < cacheTime) {
            setCachedContent(cached);
            setLoading(false);
            return;
          }
        }
        
        const content = '';
        setCachedContent(content);
        
        localStorage.setItem(cacheKey, content);
        localStorage.setItem(`${cacheKey}_meta`, JSON.stringify({ timestamp: Date.now() }));
        
        setLoading(false);
      } catch (error) {
        console.error('Cache error:', error);
        setLoading(false);
      }
    };
    
    loadCachedContent();
  }, [cacheKey, cacheTime, children]);
  
  if (loading) {
    return <Spin size="small" />;
  }
  
  if (cachedContent) {
    return <div dangerouslySetInnerHTML={{ __html: cachedContent }} />;
  }
  
  return <>{children}</>;
};

interface PerformanceSuggestionsProps {}

// 性能建议组件
export const PerformanceSuggestions: FC<PerformanceSuggestionsProps> = () => {
  const suggestions = [
    {
      title: 'Lazy Loading',
      description: 'Use LazyLoad component for below-the-fold content',
      icon: <LoadingOutlined />,
    },
    {
      title: 'Memoization',
      description: 'Wrap expensive computations in useMemo',
      icon: <CheckCircleOutlined />,
    },
    {
      title: 'Code Splitting',
      description: 'Use dynamic imports for large components',
      icon: <AlertOutlined />,
    },
    {
      title: 'Image Optimization',
      description: 'Use WebP format and lazy load images',
      icon: <DatabaseOutlined />,
    },
  ];

  return (
    <Card title="Performance Optimization Suggestions">
      <Row gutter={[16, 16]}>
        {suggestions.map((suggestion, index) => (
          <Col span={12} key={index}>
            <Card size="small" hoverable>
              <Card.Meta
                avatar={suggestion.icon}
                title={suggestion.title}
                description={suggestion.description}
              />
            </Card>
          </Col>
        ))}
      </Row>
    </Card>
  );
};

// 模拟ReactDOMServer
export const ReactDOMServer = {
  renderToString: (element: ReactNode): string => {
    return '';
  },
};

export default {
  PerformanceMonitor,
  LazyLoad,
  DebouncedInput,
  CachedComponent,
  PerformanceSuggestions,
};
