// src/contexts/PrintServerContext.js
import { createContext, useEffect, useState, useContext, useRef } from 'react'
import { message, notification } from 'antd'
import PropTypes from 'prop-types'
import { AuthContext } from './AuthContext'
import config from '../../../config'
import loglevel from 'loglevel'
const log = loglevel.getLogger('Print Server')
log.setLevel(config.logLevel)

const PrintServerContext = createContext()

const PrintServerProvider = ({ children }) => {
  const { token } = useContext(AuthContext)
  const socketRef = useRef(null)
  const [connecting, setConnecting] = useState(false)
  const [error, setError] = useState(null)
  const [messageApi, contextHolder] = message.useMessage()
  const [notificationApi] = notification.useNotification()

  useEffect(() => {
    if (token) {
      setConnecting(false)
      setError(null)
      log.debug('Token is available, connecting to print server...')
      // Clean up function
      return () => {
        if (socketRef.current) {
          log.debug('Cleaning up socket connection...')
          socketRef.current.disconnect()
          socketRef.current = null
        }
      }
    } else if (!token && socketRef.current) {
      log.debug('Token not available, disconnecting socket...')
      socketRef.current.disconnect()
      socketRef.current = null
    }
  }, [token, messageApi, notificationApi])

  return (
    <PrintServerContext.Provider
      value={{ printServer: socketRef.current, error, connecting }}
    >
      {contextHolder}
      {children}
    </PrintServerContext.Provider>
  )
}

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

export { PrintServerContext, PrintServerProvider }
