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 } from './device.js'

import { alertView, hintView, comfirmView } from '../home.jsx'

function Device({ show }) {
  const [deviceList, setDeviceList] = useState([])
  const deviceClass = useRef(null)
  const [inputValue, setInputValue] = useState('192.168.')
  const [selectedDevice, setSelectedDevice] = useState(null)
  if (!show) {
    return null
  }

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

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

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

  return (
    <>
      <div className="device-container">
        {/* 更新设备列表 */}
        <div className="device-update">
          <div className="device-update-title">设备列表</div>
          <div className="device-update-btn">
            <UpdateBtn
              onClick={(e, self) => deviceClass.current?.onRefresh(e, self)}
              title="Refresh device list"
            />
          </div>
        </div>

        {/* 设备列表 */}
        <div className="device-list">
          {deviceList.map((device, index) => (
            <ConnectItem 
              key={index} 
              ipAddress={deviceList[index]} 
              selected={selectedDevice === deviceList[index]}
              onSelect={(ip) => setSelectedDevice(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="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
