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

  const handleShip = async () => {
    setShipLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'Shipment',
        'ship'
      )
      if (result) {
        message.success('Shipment shipped successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error shipping shipment:', error)
    } finally {
      setShipLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Are you sure you want to ship this shipment?'}
      description={`Shipping shipment ${objectData?.name || objectData?._reference || objectData?._id} will update its status to shipped.`}
      onOk={handleShip}
      okText='Ship'
      okLoading={shipLoading}
    />
  )
}

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

export default ShipShipment
