// FE-EXP002: 前端性能优化
import React, { useState, useEffect, useRef } from 'react';
import { Spin, Alert, Button, Card, Row, Col, Progress, Statistic, Tooltip } from 'antd';
import { LoadingOutlined, CheckCircleOutlined, AlertOutlined, ClockCircleOutlined, ZapOutlined, DatabaseOutlined } from '@ant-design/icons';

const { Meta } = Card;

// 性能监控组件
export const PerformanceMonitor: React.FC<{
  children: React.ReactNode;
  threshold?: number;
  onPerformanceIssue?: (metrics: PerformanceMetrics) => void;
}> = ({
  children,
  threshold = 1000,
  onPerformanceIssue,
}) => {
  const [metrics, setMetrics] = useState<PerformanceMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasIssue, setHasIssue] = useState(false);
  
  useEffect(() => {
    const measurePerformance = async () => {
      try {
        // 模拟性能测量
        await new Promise(resolve => setTimeout(resolve, 100));
        
        const metrics: PerformanceMetrics = {
          loadTime: Math.random() * 1500 + 500,
          renderTime: Math.random() * 800 + 200,
          memoryUsage: Math.random() * 100 + 50,
          apiResponseTime: Math.random() * 1000 + 300,
          componentCount: Math.floor(Math.random() * 50) + 20,
        };
        
        setMetrics(metrics);
        setLoading(false);
        
        // 检查性能阈值
        if (metrics.loadTime > threshold) {
          setHasIssue(true);
          if (onPerformanceIssue) {
            onPerformanceIssue(metrics);
          }
        }
      } catch (error) {
        console.error('Performance measurement failed:', error);
        setLoading(false);
      }
    };
    
    measurePerformance();
  }, [threshold, onPerformanceIssue]);
  
  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: '40px' }}>
        <Spin size="large" indicator={<LoadingOutlined spin />} />
      </div>
    );
  }
  
  return (
    <div>
      {hasIssue && (
        <Alert
          message="Performance Warning"
          description="The component is taking longer to load than expected."
          type="warning"
          showIcon
          style={{ marginBottom: '16px' }}
        />
      )}
      
      {children}
      
      {metrics && (
        <div style={{ marginTop: '24px' }}>
          <h3>Performance Metrics</h3>
          <Row gutter={16} style={{ marginTop: '16px' }}>
            <Col span={8}>
              <Card>
                <Meta
                  avatar={<ClockCircleOutlined style={{ fontSize: '24px', color: '#1890ff' }} />}
                  title="Load Time"
                  description={`${metrics.loadTime.toFixed(0)}ms`}
                />
                <Progress 
                  percent={Math.min(100, (metrics.loadTime / 2000) * 100)} 
                  status={metrics.loadTime > threshold ? 'exception' : 'normal'} 
                  style={{ marginTop: '16px' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Meta
                  avatar={<ZapOutlined style={{ fontSize: '24px', color: '#52c41a' }} />}
                  title="Render Time"
                  description={`${metrics.renderTime.toFixed(0)}ms`}
                />
                <Progress 
                  percent={Math.min(100, (metrics.renderTime / 1000) * 100)} 
                  status={metrics.renderTime > 500 ? 'exception' : 'normal'} 
                  style={{ marginTop: '16px' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Meta
                  avatar={<DatabaseOutlined style={{ fontSize: '24px', color: '#faad14' }} />}
                  title="Memory Usage"
                  description={`${metrics.memoryUsage.toFixed(1)}MB`}
                />
                <Progress 
                  percent={Math.min(100, (metrics.memoryUsage / 200) * 100)} 
                  status={metrics.memoryUsage > 150 ? 'exception' : 'normal'} 
                  style={{ marginTop: '16px' }}
                />
              </Card>
            </Col>
          </Row>
        </div>
      )}
    </div>
  );
};

// 懒加载组件
export const LazyLoad: React.FC<{
  children: React.ReactNode;
  threshold?: number;
  placeholder?: React.ReactNode;
}> = ({
  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>
  );
};

// 防抖组件
export const DebouncedInput: React.FC<{
  value: string;
  onChange: (value: string) => void;
  delay?: number;
  placeholder?: string;
  className?: string;
}> = ({
  value,
  onChange,
  delay = 500,
  placeholder,
  className,
}) => {
  const [inputValue, setInputValue] = useState(value);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  useEffect(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    
    timeoutRef.current = setTimeout(() => {
      onChange(inputValue);
    }, delay);
    
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [inputValue, delay, onChange]);
  
  return (
    <input
      type="text"
      value={inputValue}
      onChange={(e) => setInputValue(e.target.value)}
      placeholder={placeholder}
      className={className}
      style={{
        width: '100%',
        padding: '8px 12px',
        borderRadius: '4px',
        border: '1px solid #d9d9d9',
        fontSize: '14px',
      }}
    />
  );
};

// 缓存组件
export const CachedComponent: React.FC<{
  children: React.ReactNode;
  cacheKey: string;
  cacheTime?: number;
}> = ({
  children,
  cacheKey,
  cacheTime = 5 * 60 * 1000, // 5 minutes
}) => {
  const [cachedContent, setCachedContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const loadCachedContent = async () => {
      try {
        // 尝试从localStorage获取缓存
        const cached = localStorage.getItem(cacheKey);
        const cachedMeta = localStorage.getItem(`${cacheKey}_meta`);
        
        if (cached && cachedMeta) {
          const meta = JSON.parse(cachedMeta);
          const now = Date.now();
          
          // 检查缓存是否过期
          if (now - meta.timestamp < cacheTime) {
            setCachedContent(cached);
            setLoading(false);
            return;
          }
        }
        
        // 缓存不存在或已过期，渲染组件并缓存
        const content = ReactDOMServer.renderToString(React.createElement(() => children));
        setCachedContent(content);
        
        // 保存到localStorage
        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" />;
  }
  
  return (
    <div dangerouslySetInnerHTML={{ __html: cachedContent || '' }} />
  );
};

// 性能优化建议组件
export const PerformanceSuggestions: React.FC = () => {
  const suggestions = [
    {
      title: 'Use Lazy Loading',
      description: 'Load components only when they are needed to reduce initial load time.',
      icon: <ZapOutlined />,
      severity: 'high',
    },
    {
      title: 'Optimize Images',
      description: 'Compress and resize images to reduce bandwidth usage.',
      icon: <DatabaseOutlined />,
      severity: 'medium',
    },
    {
      title: 'Minimize JavaScript',
      description: 'Bundle and minify JavaScript files to reduce file size.',
      icon: <ZapOutlined />,
      severity: 'high',
    },
    {
      title: 'Use Caching',
      description: 'Implement client-side caching to reduce API calls.',
      icon: <DatabaseOutlined />,
      severity: 'medium',
    },
  ];
  
  return (
    <div>
      <h3>Performance Optimization Suggestions</h3>
      <Row gutter={16} style={{ marginTop: '16px' }}>
        {suggestions.map((suggestion, index) => (
          <Col key={index} span={12}>
            <Card
              style={{
                borderLeft: `4px solid ${suggestion.severity === 'high' ? '#ff4d4f' : '#faad14'}`,
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                <div style={{ marginRight: '8px', color: suggestion.severity === 'high' ? '#ff4d4f' : '#faad14' }}>
                  {suggestion.icon}
                </div>
                <h4 style={{ margin: 0 }}>{suggestion.title}</h4>
              </div>
              <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>{suggestion.description}</p>
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
};

// 性能指标类型
export interface PerformanceMetrics {
  loadTime: number;
  renderTime: number;
  memoryUsage: number;
  apiResponseTime: number;
  componentCount: number;
}

// 模拟ReactDOMServer
export const ReactDOMServer = {
  renderToString: (element: any) => {
    // 简单模拟，实际项目中会使用真实的ReactDOMServer
    return '<div>' + element.props.children + '</div>';
  },
};

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