'use client'

import { createContext, useContext, useState, useEffect } from 'react'
import Toast from '../shared/Toast'

interface NotificationContextType {
  showNotification: (message: string, type: 'success' | 'error') => void
}

const NotificationContext = createContext<NotificationContextType>({
  showNotification: () => {},
})

export const useNotification = () => useContext(NotificationContext)

export function NotificationProvider({ children }: { children: React.ReactNode }) {
  const [mounted, setMounted] = useState(false)
  const [message, setMessage] = useState('')
  const [type, setType] = useState<'success' | 'error'>('success')
  const [isVisible, setIsVisible] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  const showNotification = (message: string, type: 'success' | 'error') => {
    setMessage(message)
    setType(type)
    setIsVisible(true)
    // Only auto-hide error messages
    if (type === 'error') {
      setTimeout(() => setIsVisible(false), 3000)
    }
  }

  const hideNotification = () => {
    setIsVisible(false)
  }

  if (!mounted) {
    return <>{children}</>
  }

  return (
    <NotificationContext.Provider value={{ showNotification }}>
      {children}
      <Toast 
        message={message} 
        type={type} 
        isVisible={isVisible} 
        onClose={hideNotification}
      />
    </NotificationContext.Provider>
  )
}
