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

  const handleReceive = async () => {
    setReceiveLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'Shipment',
        'receive'
      )
      if (result) {
        message.success('Shipment received successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error receiving shipment:', error)
    } finally {
      setReceiveLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Are you sure you want to receive this shipment?'}
      description={`Receiving shipment ${objectData?.name || objectData?._reference || objectData?._id} will update its status to delivered.`}
      onOk={handleReceive}
      okText='Receive'
      okLoading={receiveLoading}
    />
  )
}

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

export default ReceiveShipment
