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

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

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

  return (
    <MessageDialogView
      title='Unpublish all variants for this listing?'
      description={`Ends live marketplace listings for every active variant. On eBay the item is withdrawn and can be published again later.${
        ref ? ` (listing: ${ref})` : ''
      }`}
      onOk={handleUnpublish}
      okText='Unpublish'
      okLoading={loading}
    />
  )
}

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

export default UnpublishListing
