'use client'

import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react'
import { toast } from 'react-toastify'
import { usePathname, useRouter } from 'next/navigation'

import {
  markAsRead,
  getUnreadCount,
} from '@/lib/services/notification-services'
import '@/lib/config/echo'
import { useBroadcast } from '../hooks/useBroadcast'
import { Notification } from '../types/notification'
import { useAuth } from './AuthContext'

interface NotificationContextType {
  unreadCount: number
  isLoading: boolean
  refreshTrigger: number
  readNotificationId: number | null
  deletedNotificationId: number | null
  setReadNotificationId: (id: number | null) => void
  setDeletedNotificationId: (id: number | null) => void
  setRefreshTrigger: (value: number) => void
  getActionDetailLink: (notification: Notification) => string
  goToActionDetail: (notification: Notification) => void
  refreshNotifications: (refreshTrigger?: number) => Promise<void>
}

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

export function useNotifications() {
  const context = useContext(NotificationContext)
  if (!context) {
    throw new Error('useNotifications must be used within NotificationProvider')
  }
  return context
}

interface NotificationProviderProps {
  children: React.ReactNode
}

export function NotificationProvider({ children }: NotificationProviderProps) {
  const router = useRouter()
  const pathname = usePathname()
  const [unreadCount, setUnreadCount] = useState(0)
  const [isLoading, setIsLoading] = useState(false)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [readNotificationId, setReadNotificationId] = useState<number | null>(
    null,
  )
  const [deletedNotificationId, setDeletedNotificationId] = useState<
    number | null
  >(null)

  // Broadcast Notification States
  const audioRef = useRef<HTMLAudioElement>(null)
  const { user } = useAuth()

  // Broadcast Handlers
  useBroadcast({
    partnerId: user?.id || 0,
    onOrderPlaced: async (data) => {
      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(`/transactions`)
        },
      })
    },
    onWithdrawalProcessed: async (data) => {
      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(`/withdrawals/${data.id}`)
        },
      })
    },
    onWithdrawalRejected: async (data) => {
      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(`/withdrawals/${data.id}`)
        },
      })
    },
    onWithdrawalCompleted: async (data) => {
      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(`/withdrawals/${data.id}`)
        },
      })
    },
  })

  const refreshNotifications = useCallback(async (refreshTrigger?: number) => {
    try {
      setIsLoading(true)

      // Update Unread Count
      const unreadCountData = await getUnreadCount()
      setUnreadCount(unreadCountData)

      // Sync update for notification list in other components.
      setRefreshTrigger((prev) => (refreshTrigger ? refreshTrigger : prev + 1))
    } finally {
      setIsLoading(false)
    }
  }, [])

  const getActionDetailLink = (notification: Notification) => {
    switch (notification.type) {
      case 'partner-order-placed':
        return '/transactions'
      case 'withdrawal-processed':
      case 'withdrawal-rejected':
      case 'withdrawal-completed':
        return `/withdrawals/${notification.data.id}`
      default:
        return '/'
    }
  }

  const goToActionDetail = (notification: Notification) => {
    switch (notification.type) {
      case 'partner-order-placed':
        markAsRead(notification.data.id)

        router.push(getActionDetailLink(notification))
        break
      case 'withdrawal-processed':
      case 'withdrawal-rejected':
      case 'withdrawal-completed':
        markAsRead(notification.data.id)

        router.push(getActionDetailLink(notification))
        break
      default:
        break
    }
  }

  // Initialize Unread Count
  useEffect(() => {
    refreshNotifications()
  }, [user, pathname, refreshNotifications])

  const value: NotificationContextType = {
    unreadCount,
    isLoading,
    refreshTrigger,
    readNotificationId,
    deletedNotificationId,
    setReadNotificationId,
    setDeletedNotificationId,
    setRefreshTrigger,
    refreshNotifications,
    getActionDetailLink,
    goToActionDetail,
  }

  return (
    <NotificationContext.Provider value={value}>
      {children}

      <audio
        ref={audioRef}
        controls
        className="opacity-0 absolute pointer-events-none"
      >
        <source src="/sounds/bell-ding.mp3" type="audio/mpeg" />
      </audio>
    </NotificationContext.Provider>
  )
}
