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

// Devices 页面的业务逻辑 Hook
export function DevicesLogic() {
  // 设备列表（IP:端口格式）
  const [devices, setDevices] = useState([]);
  // 加载状态
  const [loading, setLoading] = useState(false);
  // 已连接设备集合（用于控制按钮显示）
  const [connectedDevices, setConnectedDevices] = useState(new Set());
  // 预览中的设备集合
  const [previewingDevices, setPreviewingDevices] = useState(new Set());
  // 防止重复扫描标记
  const hasScanned = useRef(false);

  // 扫描设备列表（网络扫描 + 获取已连接设备，实时显示）
  const scanDevices = async () => {
    if (!window.electronAPI || !window.electronAPI.getADBDevices) {
      console.warn('Electron API 不可用');
      setDevices([]);
      return;
    }

    setLoading(true);
    // 清空现有设备列表，准备重新扫描
    setDevices([]);
    
    // 设置实时监听设备发现事件
    const handleDeviceFound = (device) => {
      const deviceId = device?.id || device;
      if (deviceId && /^\d+\.\d+\.\d+\.\d+:\d+$/.test(deviceId)) {
        setDevices(prev => {
          // 避免重复添加
          if (prev.includes(deviceId)) {
            return prev;
          }
          console.log('实时发现设备:', deviceId);
          return [...prev, deviceId];
        });
      }
    };
    
    // 注册事件监听器
    if (window.electronAPI.onDeviceFound) {
      window.electronAPI.onDeviceFound(handleDeviceFound);
    }
    
    try {
      // 先获取当前已连接的设备
      const currentDevices = await window.electronAPI.getADBDevices();
      const currentIPPorts = currentDevices
        .map(device => device?.id || device)
        .filter(id => id && /^\d+\.\d+\.\d+\.\d+:\d+$/.test(id));
      
      if (currentIPPorts.length > 0) {
        setDevices(currentIPPorts);
      }
      
      // 然后进行网络扫描（会实时推送发现的设备）
      console.log('开始网络扫描...');
      await window.electronAPI.scanADBDevices();
      console.log('网络扫描完成');
      
      // 扫描完成后，再次获取所有设备，确保没有遗漏
      const finalDevices = await window.electronAPI.getADBDevices();
      const finalIPPorts = finalDevices
        .map(device => device?.id || device)
        .filter(id => id && /^\d+\.\d+\.\d+\.\d+:\d+$/.test(id));
      
      // 合并并去重
      setDevices(prev => {
        const allDevices = new Set([...prev, ...finalIPPorts]);
        return Array.from(allDevices);
      });
    } catch (err) {
      console.error('扫描失败:', err);
    } finally {
      setLoading(false);
      // 移除事件监听器
      if (window.electronAPI.removeDeviceFoundListener) {
        window.electronAPI.removeDeviceFoundListener();
      }
    }
  };

  // 连接设备
  const connectDevice = async (ipPort) => {
    if (!window.electronAPI || !window.electronAPI.connectADBDevice) {
      console.warn('连接设备功能不可用');
      return;
    }

    try {
      await window.electronAPI.connectADBDevice(ipPort);
      setConnectedDevices(prev => new Set([...prev, ipPort]));
    } catch (err) {
      console.error('连接设备失败:', err);
    }
  };

  // 断开设备
  const disconnectDevice = async (ipPort) => {
    if (window.electronAPI && window.electronAPI.disconnectADBDevice) {
      try {
        await window.electronAPI.disconnectADBDevice(ipPort);
      } catch (err) {
        console.error('断开设备失败:', err);
      }
    }
    setConnectedDevices(prev => {
      const newSet = new Set(prev);
      newSet.delete(ipPort);
      return newSet;
    });
    // 同时取消预览状态
    setPreviewingDevices(prev => {
      const next = new Set(prev);
      next.delete(ipPort);
      return next;
    });

    // 通知预览停止（异步避免 render 期间 setState 警告）
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent('stop-preview', { detail: { device: ipPort } }));
    }, 0);
  };

  // 切换预览/取消预览
  const togglePreview = (ipPort) => {
    setPreviewingDevices(prev => {
      const next = new Set(prev);
      const already = next.has(ipPort);
      if (already) {
        next.delete(ipPort);
      } else {
        next.add(ipPort);
      }
      // 异步通知，避免在 render 中触发别的组件 setState 警告
      setTimeout(() => {
        window.dispatchEvent(new CustomEvent(already ? 'stop-preview' : 'start-preview', { detail: { device: ipPort } }));
      }, 0);
      return next;
    });
  };

  // 页面加载时自动扫描
  useEffect(() => {
    if (!hasScanned.current) {
      hasScanned.current = true;
      scanDevices();
    }
  }, []);

  return {
    devices,
    loading,
    scanDevices,
    connectDevice,
    disconnectDevice,
    connectedDevices,
    previewingDevices,
    togglePreview,
  };
}
