import { createContext, useContext } from 'react'
import PropTypes from 'prop-types'
import { message } from 'antd'
import { isElectrobunDesktop } from '../../../electrobun-bridge'

const MessageContext = createContext()

// antd's default message top is 8px; push messages down an extra 40px in the
// desktop app so they clear the custom title bar / drag region.
const MESSAGE_TOP = isElectrobunDesktop() ? 48 : undefined

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

  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 }
