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

import { DeviceClass, setSelectedDevicesStore, setExecutionStatusCallback, getExecutionStatus } from './device.js'

function Device({ show }) {
  const [deviceList, setDeviceList] = useState([])
  const deviceClass = useRef(null)
  const [inputValue, setInputValue] = useState('192.168.')
  const [portValue, setPortValue] = useState('5555')
  const [selectedDevices, setSelectedDevices] = useState([])  // 数组，记录所有选中的 device IP
  const [executionStatus, setExecutionStatus] = useState(getExecutionStatus())
  if (!show) {
    return null
  }

  useEffect(() => {
    setExecutionStatusCallback((status) => setExecutionStatus(status))
    return () => setExecutionStatusCallback(null)
  }, [])

  // 每次显示时同步一次执行状态，确保停止后切回设备列表时灯色为灰
  useEffect(() => {
    if (show) setExecutionStatus(getExecutionStatus())
  }, [show])

  useEffect(() => {
    if (!deviceClass.current) {
      deviceClass.current = new DeviceClass()
      deviceClass.current.init(setDeviceList, inputValue, portValue, setSelectedDevices, setInputValue, setPortValue)
    }
  }, [])

  useEffect(() => {
    if (deviceClass.current) deviceClass.current.inputValue = inputValue
  }, [inputValue])

  useEffect(() => {
    if (deviceClass.current) deviceClass.current.portValue = portValue
  }, [portValue])

  useEffect(() => {
    if (deviceClass.current) deviceClass.current.currentDeviceList = deviceList
  }, [deviceList])

  useEffect(() => {
    setSelectedDevicesStore(selectedDevices)
  }, [selectedDevices])

  return (
    <>
      <div className="device-container">
        {/* 更新设备列表 */}
        <div className="device-update">
          <div className="device-update-title">设备列表</div>
          <div className="enable-wirless-connect-btn" onClick={() => deviceClass.current?.onEnableWirlessConnect()}>激活</div>
        </div>

        {/* 设备列表 */}
        <div className="device-list">
          {deviceList.map((device, index) => (
            <ConnectItem 
              key={index} 
              ipAddress={deviceList[index]} 
              selected={selectedDevices.includes(deviceList[index])}
              executionStatus={executionStatus}
              onSelect={(ip) => setSelectedDevices(prev => prev.includes(ip) ? prev.filter(x => x !== ip) : [...prev, ip])}
              onRemove={(ip) => deviceClass.current?.onRemoveDevice(ip)}
            />
          ))}
        </div>

        {/* 添加设备 */}
        <div className="device-add">
          <div className="ip-input">
            <input 
              type="text" 
              placeholder="请输入设备IP" 
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { deviceClass.current?.onAddDevice() } }}
            />
          </div>
          <div className="port-input">
            <input 
              type="text" 
              placeholder="请输入设备端口" 
              value={portValue}
              onChange={(e) => setPortValue(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { deviceClass.current?.onAddDevice() } }}
            />
          </div>
          <div className="add-btn" onClick={() => deviceClass.current?.onAddDevice()}>
            <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
