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

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

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

  return (
    <MessageDialogView
      title="Withdraw this variant from the marketplace?"
      description={`Ends the live marketplace listing for this SKU where applicable (eBay).${
        ref ? ` (variant: ${ref})` : ''
      }`}
      onOk={handleUnpublish}
      okText='Unpublish'
      okLoading={loading}
    />
  )
}

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

export default UnpublishListingVarient
