//! Tauri 命令

use crate::state::{AppState, ConnectionState, CurrentUser, DeviceInfo, HistoryItem, ConnectRequest};
use easyremote_client_core::{ClientConfig, SignalClient, SignalMessage, ScreenCapturer};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::State;
use tokio::sync::RwLock;

type AppStateHandle = Arc<RwLock<AppState>>;

/// 全局信令客户端
static SIGNAL_CLIENT: tokio::sync::OnceCell<Arc<RwLock<Option<SignalClient>>>> = tokio::sync::OnceCell::const_new();

/// 强制下线标志
static FORCE_OFFLINE_FLAG: AtomicBool = AtomicBool::new(false);

/// 当前活跃的屏幕流会话
static ACTIVE_SESSION: tokio::sync::OnceCell<Arc<RwLock<Option<ActiveScreenSession>>>> = tokio::sync::OnceCell::const_new();

/// 流媒体设置 (使用 std::sync::RwLock 以便在普通线程中使用)
#[derive(Clone)]
struct StreamSettings {
    resolution: f64,
    fps: u32,
    quality: u32,
}

impl Default for StreamSettings {
    fn default() -> Self {
        Self {
            resolution: 0.5,
            fps: 15,
            quality: 70,
        }
    }
}

/// 全局流媒体设置 (使用标准库的 RwLock)
use std::sync::RwLock as StdRwLock;
use once_cell::sync::Lazy;

static STREAM_SETTINGS: Lazy<Arc<StdRwLock<StreamSettings>>> = Lazy::new(|| {
    Arc::new(StdRwLock::new(StreamSettings::default()))
});

fn get_stream_settings_sync() -> Arc<StdRwLock<StreamSettings>> {
    STREAM_SETTINGS.clone()
}

/// 当前显示器索引
static CURRENT_DISPLAY: Lazy<Arc<std::sync::atomic::AtomicUsize>> = Lazy::new(|| {
    Arc::new(std::sync::atomic::AtomicUsize::new(0))
});

fn get_current_display() -> usize {
    CURRENT_DISPLAY.load(Ordering::SeqCst)
}

fn set_current_display(index: usize) {
    CURRENT_DISPLAY.store(index, Ordering::SeqCst);
}

/// 活跃屏幕会话
struct ActiveScreenSession {
    session_id: String,
    controller_device: String,
    stop_flag: Arc<AtomicBool>,
}

async fn get_active_session() -> &'static Arc<RwLock<Option<ActiveScreenSession>>> {
    ACTIVE_SESSION.get_or_init(|| async {
        Arc::new(RwLock::new(None))
    }).await
}

/// 获取信令客户端
async fn get_signal_client() -> &'static Arc<RwLock<Option<SignalClient>>> {
    SIGNAL_CLIENT.get_or_init(|| async {
        Arc::new(RwLock::new(None))
    }).await
}

/// 检查是否需要强制下线
pub fn check_force_offline() -> bool {
    FORCE_OFFLINE_FLAG.swap(false, Ordering::SeqCst)
}

/// 设置强制下线标志并清除登录信息
fn set_force_offline() {
    FORCE_OFFLINE_FLAG.store(true, Ordering::SeqCst);
    
    // 清除本地保存的登录信息
    let auth_path = dirs::data_dir()
        .unwrap_or_else(|| std::path::PathBuf::from("."))
        .join("easyremote")
        .join("auth.json");
    let _ = std::fs::remove_file(&auth_path);
    tracing::info!("已清除登录信息");
}

/// 启动屏幕流
async fn start_screen_streaming(session_id: String, controller_device: String, my_device_id: String) {
    tracing::info!("★★★ 启动屏幕流: session={}, controller={}, my_device={}", session_id, controller_device, my_device_id);
    println!("★★★ 启动屏幕流: session={}, controller={}, my_device={}", session_id, controller_device, my_device_id);
    
    // 检查是否已有活跃会话
    let active_session = get_active_session().await;
    {
        let mut session = active_session.write().await;
        if session.is_some() {
            tracing::warn!("已有活跃屏幕流会话，停止旧会话");
            if let Some(s) = session.as_ref() {
                s.stop_flag.store(true, Ordering::SeqCst);
            }
        }
        
        let stop_flag = Arc::new(AtomicBool::new(false));
        *session = Some(ActiveScreenSession {
            session_id: session_id.clone(),
            controller_device: controller_device.clone(),
            stop_flag: stop_flag.clone(),
        });
    }
    
    // 获取信令客户端
    let signal_client = get_signal_client().await;
    
    // 获取 stop_flag 用于停止控制
    let stop_flag_clone = {
        let session = active_session.read().await;
        session.as_ref().map(|s| s.stop_flag.clone()).unwrap_or_else(|| Arc::new(AtomicBool::new(true)))
    };
    
    // 启动屏幕捕获线程
    let session_id_capture = session_id.clone();
    let controller_device_capture = controller_device.clone();
    let _my_device_id_capture = my_device_id.clone();
    let signal_client_clone = signal_client.clone();
    
    let stream_settings = get_stream_settings_sync();
    
    std::thread::spawn(move || {
        println!("★★★ 开始创建屏幕捕获器...");
        
        // 创建一个 tokio runtime 用于发送帧
        let rt = match tokio::runtime::Runtime::new() {
            Ok(r) => r,
            Err(e) => {
                println!("★★★ 创建 tokio runtime 失败: {}", e);
                return;
            }
        };
        
        // 创建屏幕捕获器（使用当前选择的显示器）
        let display_index = get_current_display();
        println!("★★★ 使用显示器: {}", display_index);
        let mut capturer = match ScreenCapturer::new(display_index) {
            Ok(c) => {
                println!("★★★ 屏幕捕获器创建成功");
                c
            }
            Err(e) => {
                println!("★★★ 创建屏幕捕获器失败: {}", e);
                tracing::error!("创建屏幕捕获器失败: {}", e);
                return;
            }
        };
        
        let width = capturer.width();
        let height = capturer.height();
        println!("★★★ 屏幕分辨率: {}x{}", width, height);
        tracing::info!("屏幕分辨率: {}x{}", width, height);
        
        let mut frame_count = 0u64;
        let start_time = std::time::Instant::now();
        
        loop {
            // 获取当前设置
            let (resolution, fps, _quality) = {
                let s = stream_settings.read().unwrap();
                (s.resolution, s.fps, s.quality)
            };
            
            // 计算帧间隔
            let frame_interval = std::time::Duration::from_millis(1000 / fps as u64);
            
            // 检查是否需要停止
            let should_stop = stop_flag_clone.load(Ordering::SeqCst);
            
            if should_stop {
                tracing::info!("屏幕流停止");
                break;
            }
            
            // 捕获帧
            match capturer.capture_rgba() {
                Ok(Some(rgba_data)) => {
                    // 使用 image crate 压缩为 JPEG
                    let img = image::RgbaImage::from_raw(width, height, rgba_data);
                    if let Some(img) = img {
                        let mut jpeg_data = Vec::new();
                        let mut cursor = std::io::Cursor::new(&mut jpeg_data);
                        
                        // 根据设置调整分辨率
                        let scaled_width = ((width as f64) * resolution) as u32;
                        let scaled_height = ((height as f64) * resolution) as u32;
                        let scaled = image::imageops::resize(&img, scaled_width, scaled_height, image::imageops::FilterType::Nearest);
                        
                        if scaled.write_to(&mut cursor, image::ImageFormat::Jpeg).is_ok() {
                            let jpeg_len = jpeg_data.len();
                            
                            // 发送帧
                            let session_id_send = session_id_capture.clone();
                            let controller_device_send = controller_device_capture.clone();
                            let signal_client_send = signal_client_clone.clone();
                            
                            rt.block_on(async {
                                let client = signal_client_send.read().await;
                                if let Some(c) = client.as_ref() {
                                    let _ = c.send_frame(
                                        session_id_send,
                                        controller_device_send,
                                        scaled_width,
                                        scaled_height,
                                        &jpeg_data,
                                    ).await;
                                }
                            });
                            
                            frame_count += 1;
                            if frame_count % 30 == 0 {
                                let actual_fps = frame_count as f64 / start_time.elapsed().as_secs_f64();
                                println!("★★★ 屏幕流: {:.1} fps, 分辨率: {}x{}, 帧大小: {} KB", 
                                    actual_fps, scaled_width, scaled_height, jpeg_len / 1024);
                                tracing::debug!("屏幕流: {:.1} fps, 分辨率: {}x{}, 帧大小: {} KB", 
                                    actual_fps, scaled_width, scaled_height, jpeg_len / 1024);
                            }
                            // 首帧日志
                            if frame_count == 1 {
                                println!("★★★ 发送第一帧: {}x{}, {} 字节", scaled_width, scaled_height, jpeg_len);
                            }
                        }
                    }
                }
                Ok(None) => {
                    // 没有新帧
                }
                Err(e) => {
                    tracing::error!("捕获屏幕失败: {}", e);
                    break;
                }
            }
            
            // 根据设置控制帧率
            std::thread::sleep(frame_interval);
        }
        
        // 清理完成，stop_flag 已设置为 true
        println!("★★★ 屏幕流线程结束");
    });
}

/// 处理鼠标输入
fn handle_mouse_input(x: f64, y: f64, event_type: &str, button: Option<u8>, delta: Option<f64>) {
    use easyremote_client_core::InputController;
    
    // 获取当前分辨率设置以计算缩放比例
    let scale = {
        let settings = get_stream_settings_sync();
        let s = settings.read().unwrap();
        1.0 / s.resolution
    };
    let actual_x = (x * scale) as i32;
    let actual_y = (y * scale) as i32;
    
    if let Ok(mut controller) = InputController::new() {
        match event_type {
            "move" => {
                let _ = controller.move_mouse(actual_x, actual_y);
            }
            "click" => {
                let btn = match button {
                    Some(0) => easyremote_client_core::MouseButton::Left,
                    Some(2) => easyremote_client_core::MouseButton::Right,
                    Some(1) => easyremote_client_core::MouseButton::Middle,
                    _ => easyremote_client_core::MouseButton::Left,
                };
                let _ = controller.click(btn);
            }
            "down" => {
                let btn = match button {
                    Some(0) => easyremote_client_core::MouseButton::Left,
                    Some(2) => easyremote_client_core::MouseButton::Right,
                    Some(1) => easyremote_client_core::MouseButton::Middle,
                    _ => easyremote_client_core::MouseButton::Left,
                };
                let _ = controller.mouse_down(btn);
            }
            "up" => {
                let btn = match button {
                    Some(0) => easyremote_client_core::MouseButton::Left,
                    Some(2) => easyremote_client_core::MouseButton::Right,
                    Some(1) => easyremote_client_core::MouseButton::Middle,
                    _ => easyremote_client_core::MouseButton::Left,
                };
                let _ = controller.mouse_up(btn);
            }
            "scroll" => {
                if let Some(d) = delta {
                    let _ = controller.scroll(0, -(d as i32) / 3);
                }
            }
            _ => {}
        }
    }
}

/// 处理键盘输入
fn handle_keyboard_input(key: &str, event_type: &str) {
    use easyremote_client_core::InputController;
    
    if let Ok(mut controller) = InputController::new() {
        match event_type {
            "down" => {
                let _ = controller.key_down(key);
            }
            "up" => {
                let _ = controller.key_up(key);
            }
            _ => {}
        }
    }
}

/// 获取操作系统类型
fn get_os_type() -> &'static str {
    if cfg!(target_os = "windows") {
        "Windows"
    } else if cfg!(target_os = "macos") {
        "macOS"
    } else {
        "Linux"
    }
}

/// 获取操作系统版本
fn get_os_version() -> String {
    std::env::consts::OS.to_string()
}

/// 向服务端注册设备
async fn register_device_to_server(
    server_url: &str,
    device_id: &str,
    device_name: &str,
    auth_token: Option<&str>,
) -> Result<(), String> {
    let client = reqwest::Client::new();
    let http_url = server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let mut request = client
        .post(format!("{}/api/devices/register", http_url))
        .json(&serde_json::json!({
            "device_id": device_id,
            "name": device_name,
            "os_type": get_os_type(),
            "os_version": get_os_version()
        }));
    
    // 如果已登录，附带 token 以绑定设备到用户
    if let Some(token) = auth_token {
        request = request.header("Authorization", format!("Bearer {}", token));
    }
    
    let response = request.send().await.map_err(|e| e.to_string())?;
    
    if !response.status().is_success() {
        let error: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
        return Err(error["error"].as_str().unwrap_or("设备注册失败").to_string());
    }
    
    tracing::info!("设备已注册到服务端");
    Ok(())
}

/// 连接到信令服务器
async fn connect_to_signal_server(device_id: String, server_url: String) -> Result<(), String> {
    let signal_client_holder = get_signal_client().await;
    
    // 如果已连接，先断开
    {
        let mut holder = signal_client_holder.write().await;
        *holder = None;
    }
    
    // 创建新的信令客户端
    let mut signal_client = SignalClient::new(device_id.clone(), server_url.clone());
    
    // 连接到信令服务器
    let device_id_clone = device_id.clone();
    let device_id_for_callback = device_id.clone();
    match signal_client.connect(move |msg| {
        let device_id_inner = device_id_for_callback.clone();
        match msg {
            SignalMessage::HeartbeatAck => {
                tracing::debug!("收到心跳响应");
            }
            SignalMessage::ForceOffline { device_id } => {
                tracing::info!("收到强制下线命令: device_id={}", device_id);
                // 设置强制下线标志
                set_force_offline();
            }
            SignalMessage::ConnectRequest { session_id, from_device, to_device, .. } => {
                tracing::info!("★★★ 收到连接请求: session_id={}, from={}, to={}", session_id, from_device, to_device);
                println!("★★★ 收到连接请求: session_id={}, from={}, to={}", session_id, from_device, to_device);
                // 启动屏幕流
                let session_id_clone = session_id.clone();
                let from_device_clone = from_device.clone();
                let device_id_stream = device_id_inner.clone();
                std::thread::spawn(move || {
                    let rt = tokio::runtime::Runtime::new().unwrap();
                    rt.block_on(async move {
                        start_screen_streaming(session_id_clone, from_device_clone, device_id_stream).await;
                    });
                });
            }
            SignalMessage::MouseEvent { x, y, event_type, button, delta, .. } => {
                // 处理鼠标事件
                handle_mouse_input(x, y, &event_type, button, delta);
            }
            SignalMessage::KeyboardEvent { key, event_type, .. } => {
                // 处理键盘事件
                handle_keyboard_input(&key, &event_type);
            }
            SignalMessage::StreamSettings { resolution, fps, quality, .. } => {
                // 更新流媒体设置
                tracing::info!("更新流媒体设置: resolution={}, fps={}, quality={}", resolution, fps, quality);
                println!("★★★ 更新流媒体设置: resolution={}, fps={}, quality={}", resolution, fps, quality);
                let settings = get_stream_settings_sync();
                let mut s = settings.write().unwrap();
                s.resolution = resolution;
                s.fps = fps;
                s.quality = quality;
            }
            SignalMessage::GetDisplays { session_id, from_device, .. } => {
                // 获取显示器列表并返回
                println!("★★★ 收到获取显示器列表请求");
                use easyremote_client_core::capture::get_displays;
                match get_displays() {
                    Ok(displays) => {
                        println!("★★★ 获取到 {} 个显示器", displays.len());
                        for d in &displays {
                            println!("  - 显示器 {}: {}x{} (primary: {})", d.index, d.width, d.height, d.is_primary);
                        }
                        let display_msgs: Vec<_> = displays.iter().map(|d| {
                            easyremote_client_core::signal::DisplayInfoMsg {
                                index: d.index,
                                width: d.width,
                                height: d.height,
                                is_primary: d.is_primary,
                                name: format!("显示器 {} ({}x{})", d.index + 1, d.width, d.height),
                            }
                        }).collect();
                        
                        let display_count = display_msgs.len();
                        println!("★★★ 发送显示器列表响应: {} 个显示器", display_count);
                        
                        let response = SignalMessage::DisplaysList {
                            session_id,
                            from_device: device_id_inner.clone(),
                            to_device: from_device,
                            displays: display_msgs,
                            current_display: get_current_display(),
                        };
                        let signal_client_holder = SIGNAL_CLIENT.get();
                        if let Some(holder) = signal_client_holder {
                            let holder_clone = holder.clone();
                            tokio::spawn(async move {
                                let client = holder_clone.read().await;
                                if let Some(c) = client.as_ref() {
                                    let _ = c.send(response).await;
                                }
                            });
                        }
                    }
                    Err(e) => {
                        println!("★★★ 获取显示器列表失败: {}", e);
                    }
                }
            }
            SignalMessage::SwitchDisplay { display_index, from_device, session_id, .. } => {
                // 切换显示器
                println!("★★★ 收到切换显示器请求: display_index={}", display_index);
                set_current_display(display_index);
                
                // 停止当前屏幕流并重新启动
                let device_id_restart = device_id_inner.clone();
                let from_device_restart = from_device.clone();
                let session_id_restart = session_id.clone();
                
                tokio::spawn(async move {
                    // 停止当前会话
                    if let Some(holder) = ACTIVE_SESSION.get() {
                        let session = holder.read().await;
                        if let Some(s) = session.as_ref() {
                            s.stop_flag.store(true, Ordering::SeqCst);
                        }
                    }
                    
                    // 等待一会儿再重新启动
                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                    start_screen_streaming(session_id_restart, from_device_restart, device_id_restart).await;
                });
            }
            SignalMessage::SessionEnd { session_id } => {
                // 会话结束，停止屏幕流
                println!("★★★ 收到会话结束消息: session_id={}", session_id);
                tracing::info!("收到会话结束消息: session_id={}", session_id);
                
                // 停止屏幕流
                tokio::spawn(async move {
                    if let Some(holder) = ACTIVE_SESSION.get() {
                        let mut session = holder.write().await;
                        if let Some(s) = session.as_ref() {
                            s.stop_flag.store(true, Ordering::SeqCst);
                            println!("★★★ 已停止屏幕流会话");
                        }
                        *session = None;
                    }
                });
            }
            _ => {
                tracing::debug!("收到信令消息: {:?}", msg);
            }
        }
    }).await {
        Ok(_) => {
            tracing::info!("已连接到信令服务器");
            
            // 存储客户端
            let mut holder = signal_client_holder.write().await;
            *holder = Some(signal_client);
            
            // 启动心跳任务
            let holder_clone = signal_client_holder.clone();
            let device_id_for_heartbeat = device_id.clone();
            tokio::spawn(async move {
                let mut interval = tokio::time::interval(std::time::Duration::from_secs(30));
                loop {
                    interval.tick().await;
                    let holder = holder_clone.read().await;
                    if let Some(client) = holder.as_ref() {
                        if client.is_connected().await {
                            if let Err(e) = client.send_heartbeat().await {
                                tracing::warn!("发送心跳失败: {}", e);
                                break;
                            }
                            tracing::debug!("发送心跳");
                        } else {
                            tracing::info!("信令连接已断开");
                            break;
                        }
                    } else {
                        break;
                    }
                }
            });
            
            Ok(())
        }
        Err(e) => {
            tracing::warn!("连接信令服务器失败: {}", e);
            Err(format!("连接信令服务器失败: {}", e))
        }
    }
}

/// 初始化 - 验证 token、注册设备并连接信令服务器
#[tauri::command]
pub async fn initialize(state: State<'_, AppStateHandle>) -> Result<bool, String> {
    let mut app_state = state.write().await;
    let mut logged_in = false;
    
    // 如果有保存的 token，验证是否仍然有效
    if let Some(token) = &app_state.auth_token {
        let client = reqwest::Client::new();
        let server_url = app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
        
        let response = client
            .get(format!("{}/api/users/me", server_url))
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await;
        
        match response {
            Ok(resp) if resp.status().is_success() => {
                tracing::info!("Token 验证成功，用户已登录");
                logged_in = true;
            }
            _ => {
                tracing::info!("Token 已过期，需要重新登录");
                app_state.current_user = None;
                app_state.auth_token = None;
                app_state.clear_auth_data();
            }
        }
    }
    
    // 获取必要信息
    let device_id = app_state.device_id.0.clone();
    let device_name = app_state.config.device_name.clone();
    let server_url = app_state.config.server_url.clone();
    let token = app_state.auth_token.clone();
    
    drop(app_state); // 释放锁
    
    // 注册设备到服务端
    let _ = register_device_to_server(
        &server_url,
        &device_id,
        &device_name,
        token.as_deref(),
    ).await;
    
    // 连接到信令服务器（WebSocket）- 这会使设备显示为在线
    let _ = connect_to_signal_server(device_id, server_url).await;
    
    Ok(logged_in)
}

/// 获取设备信息
#[tauri::command]
pub async fn get_device_info(state: State<'_, AppStateHandle>) -> Result<DeviceInfo, String> {
    let state = state.read().await;

    Ok(DeviceInfo {
        device_id: state.device_id.0.clone(),
        device_id_formatted: state.device_id.formatted(),
        verification_code: state.verification_code.0.clone(),
        device_name: state.config.device_name.clone(),
        os_type: get_os_type().to_string(),
    })
}

/// 刷新验证码
#[tauri::command]
pub async fn refresh_verification_code(state: State<'_, AppStateHandle>) -> Result<String, String> {
    let mut state = state.write().await;
    Ok(state.refresh_code())
}

/// 用户登录
#[tauri::command]
pub async fn login(
    state: State<'_, AppStateHandle>,
    username: String,
    password: String,
) -> Result<CurrentUser, String> {
    let mut app_state = state.write().await;
    
    // 构建登录请求
    let client = reqwest::Client::new();
    let server_url = app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let response = client
        .post(format!("{}/api/auth/login", server_url))
        .json(&serde_json::json!({
            "username": username,
            "password": password,
            "device_id": app_state.device_id.0
        }))
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !response.status().is_success() {
        let error: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
        return Err(error["error"].as_str().unwrap_or("登录失败").to_string());
    }

    let result: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
    let data = &result["data"];
    
    let user = CurrentUser {
        id: data["user"]["id"].as_str().unwrap_or("").to_string(),
        username: data["user"]["username"].as_str().unwrap_or("").to_string(),
        email: data["user"]["email"].as_str().map(|s| s.to_string()),
    };
    let token = data["token"].as_str().unwrap_or("").to_string();

    app_state.set_user(user.clone(), token.clone());
    
    // 登录成功后注册设备到服务端（绑定用户）
    let device_id = app_state.device_id.0.clone();
    let device_name = app_state.config.device_name.clone();
    
    drop(app_state);
    
    let _ = register_device_to_server(&server_url, &device_id, &device_name, Some(&token)).await;
    
    Ok(user)
}

/// 用户注册
#[tauri::command]
pub async fn register(
    state: State<'_, AppStateHandle>,
    username: String,
    password: String,
    email: Option<String>,
) -> Result<CurrentUser, String> {
    let mut app_state = state.write().await;
    
    let client = reqwest::Client::new();
    let server_url = &app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let response = client
        .post(format!("{}/api/auth/register", server_url))
        .json(&serde_json::json!({
            "username": username,
            "password": password,
            "email": email
        }))
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !response.status().is_success() {
        let error: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
        return Err(error["error"].as_str().unwrap_or("注册失败").to_string());
    }

    let result: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
    let data = &result["data"];
    
    let user = CurrentUser {
        id: data["user"]["id"].as_str().unwrap_or("").to_string(),
        username: data["user"]["username"].as_str().unwrap_or("").to_string(),
        email: data["user"]["email"].as_str().map(|s| s.to_string()),
    };
    let token = data["token"].as_str().unwrap_or("").to_string();

    app_state.set_user(user.clone(), token);
    Ok(user)
}

/// 用户退出登录
#[tauri::command]
pub async fn logout(state: State<'_, AppStateHandle>) -> Result<(), String> {
    let mut state = state.write().await;
    state.logout();
    Ok(())
}

/// 获取当前用户
#[tauri::command]
pub async fn get_current_user(state: State<'_, AppStateHandle>) -> Result<Option<CurrentUser>, String> {
    let state = state.read().await;
    Ok(state.current_user.clone())
}

/// 获取用户设备列表
#[tauri::command]
pub async fn get_devices(state: State<'_, AppStateHandle>) -> Result<Vec<serde_json::Value>, String> {
    let app_state = state.read().await;
    
    let token = app_state.auth_token.as_ref()
        .ok_or("未登录")?;
    
    let client = reqwest::Client::new();
    let server_url = &app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let response = client
        .get(format!("{}/api/devices", server_url))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !response.status().is_success() {
        return Err("获取设备列表失败".to_string());
    }

    let result: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
    let devices = result["data"].as_array()
        .map(|arr| arr.clone())
        .unwrap_or_default();
    
    Ok(devices)
}

/// 移除设备
#[tauri::command]
pub async fn remove_device(
    state: State<'_, AppStateHandle>,
    device_id: String,
) -> Result<(), String> {
    let app_state = state.read().await;
    
    let token = app_state.auth_token.as_ref()
        .ok_or("未登录")?;
    
    let client = reqwest::Client::new();
    let server_url = &app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let response = client
        .delete(format!("{}/api/devices/{}", server_url, device_id))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !response.status().is_success() {
        return Err("移除设备失败".to_string());
    }

    Ok(())
}

/// 连接到目标设备
#[tauri::command]
pub async fn connect_to_device(
    state: State<'_, AppStateHandle>,
    request: ConnectRequest,
) -> Result<(), String> {
    let mut app_state = state.write().await;
    
    app_state.connection_state = ConnectionState::Connecting;
    
    // TODO: 实现实际的P2P连接逻辑
    // 这里需要：
    // 1. 连接到信令服务器
    // 2. 发送连接请求
    // 3. 进行ICE候选交换
    // 4. 建立P2P连接
    
    // 模拟连接过程
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    
    app_state.connection_state = ConnectionState::Connected {
        target_device_id: request.device_id.clone(),
        target_device_name: format!("设备 {}", request.device_id),
        connection_type: "P2P".to_string(),
    };
    
    Ok(())
}

/// 断开连接
#[tauri::command]
pub async fn disconnect(state: State<'_, AppStateHandle>) -> Result<(), String> {
    let mut app_state = state.write().await;
    
    // 获取当前会话信息
    let session_id = app_state.current_session_id.clone();
    let target_device = match &app_state.connection_state {
        ConnectionState::Connected { target_device_id, .. } => Some(target_device_id.clone()),
        _ => None,
    };
    
    // 清理状态
    app_state.connection_state = ConnectionState::Disconnected;
    app_state.current_session_id = None;
    drop(app_state);
    
    // 发送 SessionEnd 消息给被控端
    if let (Some(session_id), Some(target_device_id)) = (session_id, target_device) {
        tracing::info!("发送 SessionEnd 到设备: {}", target_device_id);
        let signal_client = get_signal_client().await;
        let client = signal_client.read().await;
        if let Some(c) = client.as_ref() {
            let _ = c.end_session(session_id).await;
        }
    }
    
    // 停止本地屏幕流（如果是被控端）
    if let Some(holder) = ACTIVE_SESSION.get() {
        let mut session = holder.write().await;
        if let Some(s) = session.as_ref() {
            s.stop_flag.store(true, Ordering::SeqCst);
            tracing::info!("已停止本地屏幕流");
        }
        *session = None;
    }
    
    Ok(())
}

/// 获取连接状态
#[tauri::command]
pub async fn get_connection_state(state: State<'_, AppStateHandle>) -> Result<ConnectionState, String> {
    let state = state.read().await;
    Ok(state.connection_state.clone())
}

/// 获取历史记录
#[tauri::command]
pub async fn get_history(
    state: State<'_, AppStateHandle>,
    page: Option<u32>,
    limit: Option<u32>,
) -> Result<Vec<HistoryItem>, String> {
    let app_state = state.read().await;
    
    let token = app_state.auth_token.as_ref()
        .ok_or("未登录")?;
    
    let client = reqwest::Client::new();
    let server_url = &app_state.config.server_url.replace("ws://", "http://").replace("wss://", "https://");
    
    let response = client
        .get(format!("{}/api/sessions/history", server_url))
        .query(&[("page", page.unwrap_or(1)), ("limit", limit.unwrap_or(20))])
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .map_err(|e| e.to_string())?;

    if !response.status().is_success() {
        return Err("获取历史记录失败".to_string());
    }

    let result: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
    let items = result["data"]["items"].as_array()
        .map(|arr| {
            arr.iter().filter_map(|item| {
                Some(HistoryItem {
                    id: item["id"].as_str()?.to_string(),
                    device_id: item["controlled_device_id"].as_str()?.to_string(),
                    device_name: item["controlled_device_name"].as_str()?.to_string(),
                    started_at: item["started_at"].as_str()?.to_string(),
                    ended_at: item["ended_at"].as_str().map(|s| s.to_string()),
                    duration: item["duration"].as_str().map(|s| s.to_string()),
                    connection_type: item["connection_type"].as_str()?.to_string(),
                })
            }).collect()
        })
        .unwrap_or_default();
    
    Ok(items)
}

/// 获取配置
#[tauri::command]
pub async fn get_config(state: State<'_, AppStateHandle>) -> Result<ClientConfig, String> {
    let state = state.read().await;
    Ok(state.config.clone())
}

/// 保存配置
#[tauri::command]
pub async fn save_config(
    state: State<'_, AppStateHandle>,
    config: ClientConfig,
) -> Result<(), String> {
    let mut state = state.write().await;
    state.config = config.clone();
    config.save().map_err(|e| e.to_string())?;
    Ok(())
}

/// 重新连接服务器
#[tauri::command]
pub async fn reconnect_server(
    state: State<'_, AppStateHandle>,
) -> Result<(), String> {
    let app_state = state.read().await;
    let server_url = app_state.config.server_url.clone();
    let device_id = app_state.device_id.0.clone();
    drop(app_state);
    
    tracing::info!("重新连接服务器: {}", server_url);
    
    // 断开现有连接
    {
        let signal_client = get_signal_client().await;
        let mut client = signal_client.write().await;
        if client.is_some() {
            *client = None;
            tracing::info!("已断开旧连接");
        }
    }
    
    // 等待一下再重连
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    
    // 重新连接
    connect_to_signal_server(device_id, server_url).await?;
    
    tracing::info!("重新连接成功");
    Ok(())
}

/// 获取开机启动状态
#[tauri::command]
pub fn get_autostart() -> Result<bool, String> {
    #[cfg(windows)]
    {
        use winreg::enums::*;
        use winreg::RegKey;
        
        let hkcu = RegKey::predef(HKEY_CURRENT_USER);
        if let Ok(run_key) = hkcu.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run") {
            return Ok(run_key.get_value::<String, _>("EasyRemote").is_ok());
        }
        Ok(false)
    }
    
    #[cfg(target_os = "macos")]
    {
        let plist_path = dirs::home_dir()
            .map(|p| p.join("Library/LaunchAgents/com.easyremote.app.plist"))
            .unwrap_or_default();
        Ok(plist_path.exists())
    }
    
    #[cfg(target_os = "linux")]
    {
        let autostart_path = dirs::config_dir()
            .map(|p| p.join("autostart/easyremote.desktop"))
            .unwrap_or_default();
        Ok(autostart_path.exists())
    }
}

/// 设置开机启动
#[tauri::command]
pub fn set_autostart(enable: bool) -> Result<(), String> {
    let exe_path = std::env::current_exe().map_err(|e| e.to_string())?;
    
    #[cfg(windows)]
    {
        use winreg::enums::*;
        use winreg::RegKey;
        
        let hkcu = RegKey::predef(HKEY_CURRENT_USER);
        let run_key = hkcu
            .open_subkey_with_flags("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_WRITE)
            .map_err(|e| e.to_string())?;
        
        if enable {
            run_key
                .set_value("EasyRemote", &exe_path.to_string_lossy().to_string())
                .map_err(|e| e.to_string())?;
        } else {
            let _ = run_key.delete_value("EasyRemote");
        }
        return Ok(());
    }
    
    #[cfg(target_os = "macos")]
    {
        let plist_path = dirs::home_dir()
            .ok_or("找不到用户目录")?
            .join("Library/LaunchAgents/com.easyremote.app.plist");
        
        if enable {
            let plist_content = format!(
                r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.easyremote.app</string>
    <key>ProgramArguments</key>
    <array>
        <string>{}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>"#,
                exe_path.to_string_lossy()
            );
            
            if let Some(parent) = plist_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
            }
            std::fs::write(&plist_path, plist_content).map_err(|e| e.to_string())?;
        } else {
            let _ = std::fs::remove_file(&plist_path);
        }
        return Ok(());
    }
    
    #[cfg(target_os = "linux")]
    {
        let autostart_dir = dirs::config_dir()
            .ok_or("找不到配置目录")?
            .join("autostart");
        let desktop_path = autostart_dir.join("easyremote.desktop");
        
        if enable {
            std::fs::create_dir_all(&autostart_dir).map_err(|e| e.to_string())?;
            
            let desktop_content = format!(
                r#"[Desktop Entry]
Type=Application
Name=EasyRemote
Exec={}
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
"#,
                exe_path.to_string_lossy()
            );
            
            std::fs::write(&desktop_path, desktop_content).map_err(|e| e.to_string())?;
        } else {
            let _ = std::fs::remove_file(&desktop_path);
        }
        return Ok(());
    }
}
