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

  const handlePost = async () => {
    setPostLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'SalesOrder',
        'post'
      )
      if (result) {
        message.success('Sales order posted successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error posting sales order:', error)
    } finally {
      setPostLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Are you sure you want to post this sales order?'}
      description={`Posting sales order ${objectData?.name || objectData?._reference || objectData?._id} will finalize it and update inventory levels where applicable.`}
      onOk={handlePost}
      okText='Post'
      okLoading={postLoading}
    />
  )
}

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

export default PostSalesOrder

