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

  const handlePost = async () => {
    setPostLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'StockTransfer',
        'post'
      )
      if (result) {
        message.success('Stock transfer posted')
        onOk(result)
      }
    } catch (error) {
      console.error('Error posting stock transfer:', error)
    } finally {
      setPostLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Post this stock transfer?'}
      description={`Receiving will move stock to the target locations, create destination stock rows, record stock events owned by this transfer, and fill in the "to" stock on each line.`}
      onOk={handlePost}
      okText='Post'
      okLoading={postLoading}
    />
  )
}

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

export default PostStockTransfer
