import './Devices.css';
import { DevicesLogic } from './Devices.js';

// Devices 组件：显示设备列表和连接/断开功能
function Devices() {
  const { devices, loading, scanDevices, connectDevice, disconnectDevice, connectedDevices, previewingDevices, togglePreview } = DevicesLogic();

  // 处理连接设备点击
  const handleConnect = async (ipPort) => {
    await connectDevice(ipPort);
  };

  // 处理断开设备点击
  const handleDisconnect = async (ipPort) => {
    await disconnectDevice(ipPort);
  };

  return (
    <div className="Devices-container">
      <div className="devices-header">
        <div className="devices-title">可连接设备</div>
        <div 
          className={`refresh-btn ${loading ? 'disabled' : ''}`}
          onClick={loading ? undefined : scanDevices}
        >
          <div className={`refresh-icon ${loading ? 'spinning' : ''}`}>↻</div>
          {loading ? '扫描中...' : '刷新'}
        </div>
      </div>
      
      <div className="devices-scroll-area">
        {devices.map((ipPort, index) => (
          <div key={index} className="device-item">
            <div className="device-info">
              <div className="device-id">{ipPort}</div>
            </div>
            <div className="device-actions">
              {!connectedDevices.has(ipPort) && (
                <div
                  className="connect-btn"
                  onClick={() => handleConnect(ipPort)}
                >
                  连接
                </div>
              )}
              {connectedDevices.has(ipPort) && (
                <div className="action-row">
                  <div
                    className={`preview-btn ${previewingDevices.has(ipPort) ? 'preview-btn--active' : ''}`}
                    onClick={() => togglePreview(ipPort)}
                  >
                    {previewingDevices.has(ipPort) ? '取消' : '预览'}
                  </div>
                  <div
                    className="disconnect-btn"
                    onClick={() => handleDisconnect(ipPort)}
                  >
                    断开
                  </div>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default Devices;
