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

  const handlePublish = async () => {
    setLoading(true)
    try {
      const result = await sendObjectFunction(objectData._id, 'Listing', 'publish')
      if (result) {
        message.success('Published successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error publishing listing:', error)
    } finally {
      setLoading(false)
    }
  }

  const ref =
    objectData?.title ||
    objectData?._reference ||
    objectData?.name ||
    objectData?._id

  return (
    <MessageDialogView
      title='Publish this listing on the marketplace?'
      description={`Each variant with a SKU will be published on the connected marketplace. Variants that are already active are skipped.${
        ref ? ` (listing: ${ref})` : ''
      }`}
      onOk={handlePublish}
      okText='Publish'
      okLoading={loading}
    />
  )
}

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

export default PublishListing
