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

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

  return (
    <MessageDialogView
      title={'Are you sure you want to post this invoice?'}
      description={`Posting invoice ${objectData?.name || objectData?._reference || objectData?._id} will set it to sent status.`}
      onOk={handlePost}
      okText='Post'
      okLoading={postLoading}
    />
  )
}

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

export default PostInvoice
