import React, { useEffect, useRef, useState } from 'react'
import './device.scss'
import UpdateBtn from './update-btn/update-btn.jsx'
import ConnectItem from './connect-item/connect-item.jsx'
import { handleRefresh, begin, handleAdd } from './device.js'

function Device({ show }) {
  const hasRun = useRef(false)
  const [deviceList, setDeviceList] = useState([])

  if (!show) {
    return null
  }

  // 当页面第一次加载出来（使用 useRef 确保只执行一次，避免 StrictMode 双重调用）
  useEffect(() => {
    if (!hasRun.current) {
      hasRun.current = true
      begin()
    }
  }, []) 

  return (
    <div className="device-container">
      {/* 更新设备列表 */}
      <div className="device-update">
        <div className="device-update-title">设备列表</div>
        <div className="device-update-btn">
          <UpdateBtn
            onClick={handleRefresh}
            title="Refresh device list"
          />
        </div>
      </div>

      {/* 设备列表 */}
      <div className="device-list">
        {deviceList.map((device, index) => (
          <ConnectItem key={index} ipAddress={device.ipAddress} />
        ))}
      </div>

      {/* 添加设备 */}
      <div className="device-add">
        <div className="ip-input">
          <input type="text" placeholder="请输入设备IP" defaultValue="192.168." />
        </div>
        <div className="add-btn" onClick={handleAdd}>
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 5V19M5 12H19" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </div>
  )
}

export default Device
