//! Linux系统托盘菜单实现
//!
//! Linux系统托盘的特殊实现，因为Linux系统托盘的行为与其他平台不同，
//! 需要专门处理以确保托盘图标和菜单能正常显示。

use crate::audio::play_prompt_tone_imp;
use crate::window::{WindowLabel, create_drawing_board_window::create_drawing_board_window_impl, create_main_window::create_main_window_impl};
use tauri::menu::{ContextMenu, MenuBuilder, MenuItemBuilder};
use tauri::{AppHandle, Runtime, tray::TrayIconBuilder};

/// 创建并设置Linux系统托盘图标和菜单
///
/// Linux系统托盘需要特殊处理，因为Linux系统托盘的行为与其他平台不同
pub fn setup_linux_tray<R: Runtime>(app: &AppHandle<R>) -> Result<(), Box<dyn std::error::Error>> {
    let tray_id = WindowLabel::MAIN_TRAY.as_ref();
    // 检查是否已经存在托盘图标，避免重复添加
    if app.tray_by_id(tray_id).is_some() {
        return Ok(());
    }

    // 创建托盘菜单
    let tray_menu = create_tray_menu(app)?;

    // 获取默认窗口图标
    let icon = app.default_window_icon().ok_or_else(|| "获取默认窗口图标失败".to_string())?.clone();

    // 创建托盘图标（关联菜单）
    let tray_icon = TrayIconBuilder::with_id(tray_id)
        .icon(icon)
        .tooltip("智评会议")
        .menu(&tray_menu)
        .build(app)
        .map_err(|e| format!("创建托盘图标失败: {}", e))?;

    // 使用 on_menu_event 处理所有菜单事件
    tray_icon.on_menu_event(move |app, event| {
        let app_handle = app.clone();
        match event.id.as_ref() {
            "main_window" => {
                play_prompt_tone_imp();
                // 切换主窗口显示/隐藏状态
                tauri::async_runtime::spawn(async move {
                    toggle_window_visibility(&app_handle, WindowLabel::MAIN).await;
                });
            }
            "drawing_board" => {
                play_prompt_tone_imp();
                // 切换画板窗口显示/隐藏状态
                tauri::async_runtime::spawn(async move {
                    toggle_window_visibility(&app_handle, WindowLabel::DRAWING_BOARD).await;
                });
            }
            "quit" => {
                play_prompt_tone_imp();
                tauri::async_runtime::spawn(async move {
                    // 直接退出，RunEvent::ExitRequested 会处理清理
                    app_handle.exit(0);
                });
            }
            _ => {}
        }
    });

    // 托盘图标创建成功
    Ok(())
}

/// 创建托盘上下文菜单
fn create_tray_menu<R: Runtime>(app: &AppHandle<R>) -> Result<impl ContextMenu, tauri::Error> {
    // 创建菜单项
    let main_window_item = MenuItemBuilder::with_id("main_window", "显示主窗口").build(app)?;
    let drawing_board_item = MenuItemBuilder::with_id("drawing_board", "显示画板").build(app)?;
    let quit_item = MenuItemBuilder::with_id("quit", "退出应用程序").build(app)?;
    // 构建菜单
    let menu_builder = MenuBuilder::new(app).item(&main_window_item).item(&drawing_board_item);
    // 添加退出项
    let menu = menu_builder.separator().item(&quit_item).build()?;

    Ok(menu)
}

/// 切换窗口显示/隐藏状态
async fn toggle_window_visibility<R: Runtime>(app: &AppHandle<R>, window_label: WindowLabel) {
    // 窗口不存在，创建窗口
    create_window(app, window_label).await;
    // 重建菜单以更新菜单项文字
    //  let _ = rebuild_tray_menu(&app);
}

/// 创建窗口
async fn create_window<R: Runtime>(app: &AppHandle<R>, window_label: WindowLabel) {
    match window_label {
        WindowLabel::MAIN => {
            if let Err(e) = create_main_window_impl(app).await {
                log::error!("创建主窗口失败: {}", e);
                // 可以考虑显示错误对话框或通知用户
            }
        }
        WindowLabel::DRAWING_BOARD => {
            if let Err(e) = create_drawing_board_window_impl(app).await {
                log::error!("创建画板窗口失败: {}", e);
                // 可以考虑显示错误对话框或通知用户
            }
        }
        _ => {
            log::error!("未知窗口标签: {}", window_label);
        }
    }
}

/// 重建托盘菜单
pub async fn rebuild_tray_menu<R: Runtime>(app: &AppHandle<R>) -> Result<(), Box<dyn std::error::Error>> {
    // 克隆 app handle 以解决生命周期问题
    let app_handle = app.clone();

    // 获取托盘图标并更新菜单
    if let Some(tray_icon) = app.tray_by_id(WindowLabel::MAIN_TRAY.as_ref()) {
        // 创建新的托盘菜单
        let main_window_item = MenuItemBuilder::with_id("main_window", "显示主窗口").build(&app_handle)?;
        let drawing_board_item = MenuItemBuilder::with_id("drawing_board", "显示画板").build(&app_handle)?;
        let quit_item = MenuItemBuilder::with_id("quit", "退出应用程序").build(&app_handle)?;
        // 构建菜单
        let menu = MenuBuilder::new(&app_handle)
            .item(&main_window_item)
            .item(&drawing_board_item)
            .separator()
            .item(&quit_item)
            .build()?;

        tray_icon.set_menu(Some(menu)).map_err(|e| format!("设置托盘菜单失败: {}", e))?;
    }

    Ok(())
}
