"use client"

import React, { createContext, useContext, useState, ReactNode } from "react"
import { INotiRequest } from "@/type/Common"
import NotifyCustom from "@component/Common/NotifyCustom"
import { CometChatIncomingCall } from "@cometchat//chat-uikit-react"

interface NotificationContextType {
  notify: (config: INotiRequest) => void
}

const NotificationContext = createContext<NotificationContextType | undefined>(undefined)

export const NotificationProvider = ({ children }: { children: ReactNode }) => {
  const [notiConfig, setNotiConfig] = useState<INotiRequest | null>(null)
  const [isOpen, setIsOpen] = useState(false)

  const notify = (config: INotiRequest) => {
    setNotiConfig(config)
    setIsOpen(true)
  }

  const handleClose = () => {
    setIsOpen(false)
  }

  return (
    <NotificationContext.Provider value={{ notify }}>
      {children}
      {notiConfig && (
        <NotifyCustom
          type={notiConfig.type}
          message={notiConfig.message}
          description={notiConfig.description}
          isOpen={isOpen}
          onclose={handleClose}
        />
      )}
      <CometChatIncomingCall />
    </NotificationContext.Provider>
  )
}

export const useNotificationContext = () => {
  const context = useContext(NotificationContext)
  if (!context) {
    throw new Error("useNotificationContext must be used within a NotificationProvider")
  }
  return context
}
