import { useState, useEffect, useCallback } from 'react';

export type PerformanceLevel = 'high' | 'medium' | 'low';

interface PerformanceConfig {
  level: PerformanceLevel;
  enableAnimations: boolean;
  enableStagger: boolean;
  maxStaggerItems: number;
  reduceMotion: boolean;
  enableComplexEffects: boolean;
}

const defaultConfig: Record<PerformanceLevel, PerformanceConfig> = {
  high: {
    level: 'high',
    enableAnimations: true,
    enableStagger: true,
    maxStaggerItems: 50,
    reduceMotion: false,
    enableComplexEffects: true,
  },
  medium: {
    level: 'medium',
    enableAnimations: true,
    enableStagger: true,
    maxStaggerItems: 20,
    reduceMotion: false,
    enableComplexEffects: false,
  },
  low: {
    level: 'low',
    enableAnimations: false,
    enableStagger: false,
    maxStaggerItems: 0,
    reduceMotion: true,
    enableComplexEffects: false,
  },
};

export function usePerformance() {
  const [config, setConfig] = useState<PerformanceConfig>(defaultConfig.medium);
  const [isReady, setIsReady] = useState(false);

  // 检测设备性能
  useEffect(() => {
    const detectPerformance = () => {
      // 检查是否偏好减少动画
      const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      if (prefersReducedMotion) {
        setConfig(defaultConfig.low);
        setIsReady(true);
        return;
      }

      // 检测硬件性能
      const memory = (navigator as any).deviceMemory;
      const cores = navigator.hardwareConcurrency || 2;
      
      // 检测是否为低性能设备
      const isLowEnd = 
        (memory && memory <= 4) ||
        (cores <= 2) ||
        /Android 4|Android 5|Android 6/i.test(navigator.userAgent) ||
        /iPhone OS [456]_/i.test(navigator.userAgent);

      // 检测是否为高性能设备
      const isHighEnd = 
        (memory && memory >= 8) &&
        (cores >= 6);

      if (isLowEnd) {
        setConfig(defaultConfig.low);
      } else if (isHighEnd) {
        setConfig(defaultConfig.high);
      } else {
        setConfig(defaultConfig.medium);
      }
      
      setIsReady(true);
    };

    detectPerformance();

    // 监听性能偏好变化
    const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
    const handleChange = (e: MediaQueryListEvent) => {
      if (e.matches) {
        setConfig(defaultConfig.low);
      }
    };
    
    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);

  // 手动设置性能级别
  const setPerformanceLevel = useCallback((level: PerformanceLevel) => {
    setConfig(defaultConfig[level]);
  }, []);

  // 获取动画配置
  const getAnimationProps = useCallback((baseDelay: number = 0, index: number = 0) => {
    if (!config.enableAnimations) {
      return {};
    }

    if (!config.enableStagger || index >= config.maxStaggerItems) {
      return {
        initial: { opacity: 0 },
        animate: { opacity: 1 },
        transition: { duration: 0.2 },
      };
    }

    const delay = Math.min(index * 0.03, 0.15) + baseDelay;
    return {
      initial: { opacity: 0, y: 8 },
      animate: { opacity: 1, y: 0 },
      transition: { duration: 0.25, delay },
    };
  }, [config]);

  // 获取页面过渡配置
  const getPageTransition = useCallback(() => {
    if (!config.enableAnimations) {
      return {
        initial: {},
        animate: {},
        exit: {},
        transition: { duration: 0 },
      };
    }

    return {
      initial: { opacity: 0 },
      animate: { opacity: 1 },
      exit: { opacity: 0 },
      transition: { duration: 0.2 },
    };
  }, [config]);

  return {
    config,
    isReady,
    setPerformanceLevel,
    getAnimationProps,
    getPageTransition,
  };
}

export default usePerformance;
