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 ConfirmSalesOrder = ({ onOk, objectData }) => {
  const [confirmLoading, setConfirmLoading] = useState(false)
  const { sendObjectFunction } = useContext(ApiServerContext)

  const handleConfirm = async () => {
    setConfirmLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'SalesOrder',
        'confirm'
      )
      if (result) {
        message.success('Sales order confirmed successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error confirming sales order:', error)
    } finally {
      setConfirmLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Are you sure you want to confirm this sales order?'}
      description={`Confirming sales order ${objectData?.name || objectData?._reference || objectData?._id} will update its status to confirmed.`}
      onOk={handleConfirm}
      okText='Confirm'
      okLoading={confirmLoading}
    />
  )
}

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

export default ConfirmSalesOrder
