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 HintView from '../public/hint-view/hint-view.jsx'
import Alert from '../public/alert-view/alert-view.jsx'
import ComfirmView from '../public/comfirm-view/comfirm-view.jsx'
import { DeviceClass } from './device.js'
import hintView from '../public/hint-view/hint-view.js'
import alertView from '../public/alert-view/alert-view.js'
import comfirmView from '../public/comfirm-view/comfirm-view.js'
import { createHandleClose } from '../home.js'

function Device({ show }) {
  const [deviceList, setDeviceList] = useState([])
  const [showHintView, setShowHintView] = useState(false)
  const [showAlert, setShowAlert] = useState(false)
  const [showComfirmView, setShowComfirmView] = useState(false)
  const deviceClass = useRef(null)

  if (!show) {
    return null
  }

  // 初始化 deviceClass，确保在渲染时就有值
  if (!deviceClass.current) {
    deviceClass.current = new DeviceClass(setDeviceList)
  }

  // 设置 API 对象的回调函数并初始化 deviceClass
  useEffect(() => {
    hintView.setShowCallback(setShowHintView)
    alertView.setShowCallback(setShowAlert)
    comfirmView.setShowCallback(setShowComfirmView)
    
    // 回调设置完成后，初始化 deviceClass
    if (deviceClass.current && !deviceClass.current._initialized) {
      deviceClass.current.init()
    }
  }, [])

  // 当 setDeviceList 更新时，同步更新 deviceClass 的引用
  useEffect(() => {
    if (deviceClass.current) {
      deviceClass.current.setDeviceList = setDeviceList
    }
  }, [setDeviceList])

  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?.handleRefresh(e, self)}
              title="Refresh device list"
            />
          </div>
        </div>

        {/* 设备列表 */}
        <div className="device-list">
          {deviceList.map((device, index) => (
            <ConnectItem 
              key={index} 
              ipAddress={deviceList[index]} 
              onRemove={(ip) => deviceClass.current?.removeDevice(ip)}
            />
          ))}
        </div>

        {/* 添加设备 */}
        <div className="device-add">
          <div className="ip-input">
            <input type="text" placeholder="请输入设备IP" defaultValue="192.168." />
          </div>
          <div className="add-btn" onClick={() => deviceClass.current?.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>

      {showHintView && <HintView show={showHintView} onClose={createHandleClose(setShowHintView)} title={hintView._title} content={hintView._content} />}
      {showAlert && <Alert show={showAlert} onClose={createHandleClose(setShowAlert)} title={alertView._title} content={alertView._content} />}
      {showComfirmView && <ComfirmView show={showComfirmView} onClose={() => {
        comfirmView.hide()
        if (comfirmView._onCancel) {
          comfirmView._onCancel()
        }
      }} onConfirm={() => {
        console.log('ComfirmView onConfirm clicked, _onConfirm:', comfirmView._onConfirm)
        if (comfirmView._onConfirm) {
          comfirmView._onConfirm()
        } else {
          console.warn('comfirmView._onConfirm is null')
        }
      }} title={comfirmView._title} content={comfirmView._content} />}
    </>
  )
}

export default Device
