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

// 键盘输入事件处理：将电脑键盘输入转换为真机输入
export function useInputEvents(currentDevice, isInputModeActive = true) {
  const inputBufferRef = useRef('');
  const isComposingRef = useRef(false);

  // 发送文字到设备
  const sendTextToDevice = useCallback(async (text) => {
    if (!currentDevice || !text || !window.electronAPI || !window.electronAPI.sendText) {
      return;
    }

    try {
      const result = await window.electronAPI.sendText(currentDevice, text);
      if (!result?.success) {
        console.error('发送文字失败:', result?.error);
      }
    } catch (err) {
      console.error('发送文字异常:', err);
    }
  }, [currentDevice]);

  // 处理键盘输入
  const handleKeyDown = useCallback((e) => {
    // 如果输入模式未激活，不处理
    if (!isInputModeActive || !currentDevice) {
      return;
    }

    // 忽略系统快捷键（如 Ctrl+C, Ctrl+V 等）
    if (e.ctrlKey || e.metaKey || e.altKey) {
      // 但允许 Ctrl+V 粘贴
      if ((e.ctrlKey || e.metaKey) && e.key === 'v' && !e.shiftKey && !e.altKey) {
        e.preventDefault();
        // 从剪贴板获取内容
        navigator.clipboard.readText().then(text => {
          if (text) {
            sendTextToDevice(text);
          }
        }).catch(err => {
          console.error('读取剪贴板失败:', err);
        });
      }
      return;
    }

    // 处理特殊键
    switch (e.key) {
      case 'Enter':
        e.preventDefault();
        sendTextToDevice('\n');
        break;
      case 'Backspace':
        e.preventDefault();
        // 发送删除键事件
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_DEL');
        }
        break;
      case 'Delete':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_FORWARD_DEL');
        }
        break;
      case 'ArrowLeft':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_DPAD_LEFT');
        }
        break;
      case 'ArrowRight':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_DPAD_RIGHT');
        }
        break;
      case 'ArrowUp':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_DPAD_UP');
        }
        break;
      case 'ArrowDown':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_DPAD_DOWN');
        }
        break;
      case 'Tab':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_TAB');
        }
        break;
      case 'Escape':
        e.preventDefault();
        if (window.electronAPI && window.electronAPI.sendKeyEvent) {
          window.electronAPI.sendKeyEvent(currentDevice, 'KEYCODE_BACK');
        }
        break;
      default:
        // 普通字符，在 keypress 事件中处理
        break;
    }
  }, [currentDevice, isInputModeActive, sendTextToDevice]);

  // 处理字符输入（keypress 事件可以获取实际字符）
  const handleKeyPress = useCallback((e) => {
    if (!isInputModeActive || !currentDevice) {
      return;
    }

    // 忽略系统快捷键
    if (e.ctrlKey || e.metaKey || e.altKey) {
      return;
    }

    // 获取输入的字符
    const char = e.key;
    
    // 忽略控制字符（除了换行）
    if (char.length === 1 && char.charCodeAt(0) < 32 && char !== '\n') {
      return;
    }

    e.preventDefault();
    
    // 发送单个字符
    sendTextToDevice(char);
  }, [currentDevice, isInputModeActive, sendTextToDevice]);

  // 监听全局键盘事件
  useEffect(() => {
    if (!isInputModeActive || !currentDevice) {
      return;
    }

    // 添加键盘事件监听
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keypress', handleKeyPress);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keypress', handleKeyPress);
    };
  }, [isInputModeActive, currentDevice, handleKeyDown, handleKeyPress]);

  return {
    // 可以返回一些控制函数，如果需要的话
  };
}

