import { createContext, useContext } from 'react'
import PropTypes from 'prop-types'
import { message } from 'antd'

const MessageContext = createContext()

export const MessageProvider = ({ children }) => {
  const [msgApi, contextHolder] = message.useMessage()

  const showMessage = (type, content, options = {}) => {
    return msgApi.open({
      type,
      content,
      ...options
    })
  }

  const showSuccess = (content, options = {}) =>
    showMessage('success', content, options)
  const showInfo = (content, options = {}) =>
    showMessage('info', content, options)
  const showWarning = (content, options = {}) =>
    showMessage('warning', content, options)
  const showError = (content, options = {}) =>
    showMessage('error', content, options)
  const showLoading = (content, options = {}) =>
    showMessage('loading', content, options)

  return (
    <MessageContext.Provider
      value={{
        msgApi,
        showSuccess,
        showInfo,
        showWarning,
        showError,
        showLoading
      }}
    >
      {contextHolder}
      {children}
    </MessageContext.Provider>
  )
}

MessageProvider.propTypes = {
  children: PropTypes.node.isRequired
}

// eslint-disable-next-line react-refresh/only-export-components
export const useMessageContext = () => {
  const context = useContext(MessageContext)
  if (!context) {
    throw new Error('useMessageContext must be used within a MessageProvider')
  }
  return context
}

export { MessageContext }
