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 RestartPrinter = ({ 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: 'restartPrinter'
      })
      message.success('Printer restart initiated')
      onOk()
    } catch (error) {
      console.error('Error restarting printer:', error)
    } finally {
      setRestartLoading(false)
    }
  }

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

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

export default RestartPrinter
