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

  return (
    <MessageDialogView
      title='Are you sure you want to restart Moonraker?'
      description={`Restarting Moonraker on ${objectData?.name || objectData?._id} will restart the Moonraker service. The printer will be temporarily unavailable.`}
      onOk={handleRestart}
      okText='Restart Moonraker'
      okLoading={restartLoading}
    />
  )
}

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

export default RestartMoonraker
