import { useState, useContext } from 'react'
import PropTypes from 'prop-types'
import { ApiServerContext } from '../../context/ApiServerContext'
import { message } from 'antd'
import MessageDialogView from '../../common/MessageDialogView.jsx'

const RestartPrinterFirmware = ({ onOk, objectData }) => {
  const [restartLoading, setRestartLoading] = useState(false)
  const { connected, sendObjectAction } = useContext(ApiServerContext)

  const handleRestart = async () => {
    if (!connected) {
      message.error('Not connected to server')
      return
    }

    setRestartLoading(true)
    try {
      sendObjectAction(objectData._id, 'printer', {
        type: 'restartPrinterFirmware'
      })
      message.success('Printer firmware restart initiated')
      onOk()
    } catch (error) {
      console.error('Error restarting printer firmware:', error)
    } finally {
      setRestartLoading(false)
    }
  }

  return (
    <MessageDialogView
      title='Are you sure you want to restart the printer firmware?'
      description={`Restarting firmware on ${objectData?.name || objectData?._id} will restart the printer's firmware. Any active print jobs may be interrupted.`}
      onOk={handleRestart}
      okText='Restart Firmware'
      okLoading={restartLoading}
    />
  )
}

RestartPrinterFirmware.propTypes = {
  onOk: PropTypes.func.isRequired,
  objectData: PropTypes.object
}

export default RestartPrinterFirmware
