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

  const handleAuthorise = async () => {
    setAuthoriseLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'Payment',
        'authorise'
      )
      if (result) {
        message.success('Payment authorised successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error authorising payment:', error)
    } finally {
      setAuthoriseLoading(false)
    }
  }

  return (
    <MessageDialogView
      title={'Are you sure you want to authorise this payment?'}
      description={`Authorising payment ${objectData?.name || objectData?._reference || objectData?._id} will update its status to authorised.`}
      onOk={handleAuthorise}
      okText='Authorise'
      okLoading={authoriseLoading}
    />
  )
}

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

export default AuthorisePayment
