import { getCurrentWindow } from '@tauri-apps/api/window';
import { LogicalSize } from '@tauri-apps/api/window';

/**
 * 屏幕适配配置
 */
interface ScreenAdaptationConfig {
  /** 最小宽度 */
  minWidth: number;
  /** 最小高度 */
  minHeight: number;
  /** 最大宽度比例（相对于屏幕宽度） */
  maxWidthRatio: number;
  /** 最大高度比例（相对于屏幕高度） */
  maxHeightRatio: number;
  /** 默认宽度比例 */
  defaultWidthRatio: number;
  /** 默认高度比例 */
  defaultHeightRatio: number;
}

/**
 * 屏幕信息
 */
interface ScreenInfo {
  width: number;
  height: number;
  scaleFactor: number;
}

/**
 * 窗口尺寸
 */
interface WindowSize {
  width: number;
  height: number;
}

/**
 * 屏幕适配服务
 * 根据用户屏幕尺寸动态调整窗口大小
 */
export class ScreenAdaptationService {
  private static instance: ScreenAdaptationService;
  private config: ScreenAdaptationConfig;

  private constructor() {
    this.config = {
      minWidth: 800,
      minHeight: 600,
      maxWidthRatio: 0.9,
      maxHeightRatio: 0.9,
      defaultWidthRatio: 0.75,
      defaultHeightRatio: 0.8,
    };
  }

  public static getInstance(): ScreenAdaptationService {
    if (!ScreenAdaptationService.instance) {
      ScreenAdaptationService.instance = new ScreenAdaptationService();
    }
    return ScreenAdaptationService.instance;
  }

  /**
   * 获取屏幕信息
   */
  private async getScreenInfo(): Promise<ScreenInfo> {
    try {
      // 获取主显示器信息
      const { availableMonitors } = await import('@tauri-apps/api/window');
      const monitors = await availableMonitors();
      const primaryMonitor = monitors.find(m => m.name === 'primary') || monitors[0];
      
      if (primaryMonitor) {
        return {
          width: primaryMonitor.size.width,
          height: primaryMonitor.size.height,
          scaleFactor: primaryMonitor.scaleFactor,
        };
      }
    } catch (error) {
      console.warn('无法获取显示器信息，使用默认值:', error);
    }

    // 回退到浏览器API（如果可用）
    if (typeof globalThis !== 'undefined' && 'screen' in globalThis) {
      const screen = (globalThis as any).screen;
      return {
        width: screen.availWidth || 1920,
        height: screen.availHeight || 1080,
        scaleFactor: (globalThis as any).devicePixelRatio || 1,
      };
    }

    // 默认值
    return {
      width: 1920,
      height: 1080,
      scaleFactor: 1,
    };
  }

  /**
   * 计算最佳窗口尺寸
   */
  private calculateOptimalSize(screenInfo: ScreenInfo): WindowSize {
    const { width: screenWidth, height: screenHeight } = screenInfo;
    
    // 计算基于比例的尺寸
    let width = Math.floor(screenWidth * this.config.defaultWidthRatio);
    let height = Math.floor(screenHeight * this.config.defaultHeightRatio);

    // 应用最小尺寸限制
    width = Math.max(width, this.config.minWidth);
    height = Math.max(height, this.config.minHeight);

    // 应用最大尺寸限制
    const maxWidth = Math.floor(screenWidth * this.config.maxWidthRatio);
    const maxHeight = Math.floor(screenHeight * this.config.maxHeightRatio);
    
    width = Math.min(width, maxWidth);
    height = Math.min(height, maxHeight);

    return { width, height };
  }

  /**
   * 应用屏幕适配
   */
  public async applyScreenAdaptation(): Promise<void> {
    try {
      const window = getCurrentWindow();
      const screenInfo = await this.getScreenInfo();
      const optimalSize = this.calculateOptimalSize(screenInfo);

      console.log('屏幕信息:', screenInfo);
      console.log('计算的最佳窗口尺寸:', optimalSize);

      // 设置窗口尺寸
      await window.setSize(new LogicalSize(optimalSize.width, optimalSize.height));

      // 居中显示
      await window.center();

      // 设置最小尺寸
      await window.setMinSize(new LogicalSize(this.config.minWidth, this.config.minHeight));

      console.log('屏幕适配完成');
    } catch (error) {
      console.error('屏幕适配失败:', error);
    }
  }

  /**
   * 根据屏幕类型获取预设配置
   */
  public async getScreenTypeConfig(): Promise<{
    type: 'small' | 'medium' | 'large' | 'ultrawide';
    config: Partial<ScreenAdaptationConfig>;
  }> {
    const screenInfo = await this.getScreenInfo();
    const { width, height } = screenInfo;
    const aspectRatio = width / height;

    // 小屏幕 (< 1366x768)
    if (width < 1366 || height < 768) {
      return {
        type: 'small',
        config: {
          defaultWidthRatio: 0.95,
          defaultHeightRatio: 0.9,
          minWidth: 800,
          minHeight: 600,
        },
      };
    }

    // 超宽屏 (21:9 或更宽)
    if (aspectRatio >= 2.3) {
      return {
        type: 'ultrawide',
        config: {
          defaultWidthRatio: 0.7,
          defaultHeightRatio: 0.85,
          minWidth: 1200,
          minHeight: 700,
        },
      };
    }

    // 大屏幕 (>= 1920x1080)
    if (width >= 1920 && height >= 1080) {
      return {
        type: 'large',
        config: {
          defaultWidthRatio: 0.75,
          defaultHeightRatio: 0.8,
          minWidth: 1000,
          minHeight: 700,
        },
      };
    }

    // 中等屏幕
    return {
      type: 'medium',
      config: {
        defaultWidthRatio: 0.85,
        defaultHeightRatio: 0.85,
        minWidth: 900,
        minHeight: 650,
      },
    };
  }

  /**
   * 应用智能适配（根据屏幕类型自动调整）
   */
  public async applySmartAdaptation(): Promise<void> {
    try {
      const { type, config } = await this.getScreenTypeConfig();
      
      // 更新配置
      this.config = { ...this.config, ...config };
      
      console.log(`检测到屏幕类型: ${type}`);
      console.log('应用配置:', config);
      
      // 应用适配
      await this.applyScreenAdaptation();
    } catch (error) {
      console.error('智能适配失败:', error);
    }
  }

  /**
   * 更新配置
   */
  public updateConfig(newConfig: Partial<ScreenAdaptationConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  /**
   * 获取当前配置
   */
  public getConfig(): ScreenAdaptationConfig {
    return { ...this.config };
  }
}

// 导出单例实例
export const screenAdaptationService = ScreenAdaptationService.getInstance();
