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

  const handleSync = async () => {
    setSyncLoading(true)
    try {
      const result = await sendObjectFunction(
        objectData._id,
        'Marketplace',
        'sync/orders'
      )
      if (result) {
        message.success('Orders synced successfully')
        onOk(result)
      }
    } catch (error) {
      console.error('Error syncing orders:', error)
    } finally {
      setSyncLoading(false)
    }
  }

  return (
    <MessageDialogView
      title='Sync orders from marketplace?'
      description={`This will sync orders from ${objectData?.name || objectData?._reference || objectData?._id} to your local database.`}
      onOk={handleSync}
      okText='Sync'
      okLoading={syncLoading}
    />
  )
}

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

export default SyncOrders
