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

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

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

  return (
    <MessageDialogView
      title='Publish this listing variant on the marketplace?'
      description={`Publishes this SKU on the connected marketplace so the item goes live when a draft listing exists (eBay).${
        ref ? ` (variant: ${ref})` : ''
      }`}
      onOk={handlePublish}
      okText='Publish'
      okLoading={loading}
    />
  )
}

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

export default PublishListingVarient
