'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 { Notification } from '../types/notification'
import { useAuth } from './AuthContext'
import { useOrderBroadcast } from '../hooks/useOrderBroadcast'
import { useRescheduleBroadcast } from '../hooks/useRescheduleBroadcast'
import { useRefundBroadcast } from '../hooks/useRefundBroadcast'
import { useConfirmOrderBroadcast } from '../hooks/useConfirmOrderBroadcast'
import { useWithdrawalBroadcast } from '../hooks/useWithdrawalBroadcast'

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
  setMerchantId: (merchantId?: 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 [merchantId, setMerchantId] = useState<number | undefined>(undefined)
  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, userManagedMerchants } = useAuth()

  // Orders - Broadcast Notification
  useOrderBroadcast({
    onOrderPlaced: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(
            `/merchant-dashboard/${data.merchantId}/orders/${data.orderId}`,
          )
        },
      })
    },
    onOrderPaid: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      // Redirect URL based on booking method
      let redirectURL = ''

      if (data.bookingMethod === 'offline') {
        redirectURL = `/merchant-dashboard/${data.merchantId}/bookings/${data.orderId}`
      } else {
        redirectURL = `/merchant-dashboard/${data.merchantId}/orders/${data.orderId}`
      }

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => router.push(redirectURL),
      })
    },
    onPaymentFailed: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      // Redirect URL based on booking method
      let redirectURL = ''

      if (data.bookingMethod === 'offline') {
        redirectURL = `/merchant-dashboard/${data.merchantId}/bookings/${data.orderId}`
      } else {
        redirectURL = `/merchant-dashboard/${data.merchantId}/orders/${data.orderId}`
      }

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => router.push(redirectURL),
      })
    },
  })

  // Reschedules - Broadcast Notification
  useRescheduleBroadcast({
    onRescheduleRequested: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      // Reschedule Created by Customer
      if (data.createdById === null) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/reschedules/${data.rescheduleId}`,
            )
          },
        })
      }

      // Reschedule Created by Supervisor
      if (
        (user?.role === 'manager' || user?.role === 'general_manager') &&
        data.createdById !== null
      ) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/reschedules/${data.rescheduleId}`,
            )
          },
        })
      }
    },
    onRescheduleApproved: async (data) => {
      if (user?.role === 'supervisor' && data.createdById === user.id) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/reschedules/${data.rescheduleId}`,
            )
          },
        })
      }
    },
    onRescheduleRejected: async (data) => {
      if (user?.role === 'supervisor' && data.createdById === user.id) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/reschedules/${data.rescheduleId}`,
            )
          },
        })
      }
    },
  })

  // Refunds - Broadcast Notification
  useRefundBroadcast({
    onRefundRequested: async (data) => {
      if (user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      // Refund Created by Customer
      if (data.createdById === null) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/refunds/${data.refundId}`,
            )
          },
        })
      }

      // Refund Created by Supervisor or Manager
      if (user?.role === 'accounting' && data.createdById !== null) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/refunds/${data.refundId}`,
            )
          },
        })
      }
    },
    onRefundApproved: async (data) => {
      if (
        user &&
        ['manager', 'general_manager', 'supervisor'].includes(user.role) &&
        data.createdById === user.id
      ) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/refunds/${data.refundId}`,
            )
          },
        })
      }
    },
    onRefundRejected: async (data) => {
      if (
        user &&
        ['manager', 'general_manager', 'supervisor'].includes(user.role) &&
        data.createdById === user.id
      ) {
        await refreshNotifications()

        audioRef.current?.play()

        toast.info(data.message, {
          autoClose: 3000,
          onClick: () => {
            router.push(
              `/merchant-dashboard/${data.merchantId}/refunds/${data.refundId}`,
            )
          },
        })
      }
    },
  })

  // Order Confirmations - Broadcast Notification
  useConfirmOrderBroadcast({
    onActivityConfirmed: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(
            `/merchant-dashboard/${data.merchantId}/order-confirmations/activity`,
          )
        },
      })
    },
    onFastboatConfirmed: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(
            `/merchant-dashboard/${data.merchantId}/order-confirmations/fastboat`,
          )
        },
      })
    },
    onTourPackageConfirmed: async (data) => {
      if (user?.role === 'accounting' || user?.role === 'super_admin') return
      if (!userManagedMerchants.includes(data.merchantId)) return

      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(
            `/merchant-dashboard/${data.merchantId}/order-confirmations/tour-package`,
          )
        },
      })
    },
  })

  // Withdrawal Broadcast Handlers
  useWithdrawalBroadcast({
    onWithdrawalRequest: async (data) => {
      if (
        user?.role !== 'manager' &&
        user?.role !== 'general_manager' &&
        user?.role !== 'accounting'
      )
        return

      await refreshNotifications()

      audioRef.current?.play()

      toast.info(data.message, {
        autoClose: 3000,
        onClick: () => {
          router.push(`/withdrawals/${data.id}`)
        },
      })
    },
    onWithdrawalCancelled: async (data) => {
      if (
        user?.role !== 'manager' &&
        user?.role !== 'general_manager' &&
        user?.role !== 'accounting'
      )
        return

      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(merchantId)
        setUnreadCount(unreadCountData)

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

  const getActionDetailLink = (notification: Notification) => {
    switch (notification.type) {
      case 'approved-refund':
      case 'rejected-refund':
      case 'refund-request':
        return `/merchant-dashboard/${notification.data.merchant_id}/refunds/${notification.data.id}`
      case 'reschedule-request':
      case 'approved-reschedule':
      case 'rejected-reschedule':
        return `/merchant-dashboard/${notification.data.merchant_id}/reschedules/${notification.data.id}`
      case 'new-order':
      case 'order-paid':
      case 'failed-payment':
        return notification.data.booking_method === 'online'
          ? `/merchant-dashboard/${notification.data.merchant_id}/orders/${notification.data.id}`
          : `/merchant-dashboard/${notification.data.merchant_id}/bookings/${notification.data.id}`
      case 'fastboat-order-confirmation':
        return `/merchant-dashboard/${notification.data.merchant_id}/order-confirmations/fastboat`
      case 'activity-order-confirmation':
        return `/merchant-dashboard/${notification.data.merchant_id}/order-confirmations/activity`
      case 'tour-package-order-confirmation':
        return `/merchant-dashboard/${notification.data.merchant_id}/order-confirmations/tour-package`
      case 'withdrawal-request':
      case 'withdrawal-cancelled':
        return `/withdrawals/${notification.data.id}`
      default:
        return '/'
    }
  }

  const goToActionDetail = (notification: Notification) => {
    switch (notification.type) {
      case 'refund-request':
      case 'approved-refund':
      case 'rejected-refund':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))
      case 'reschedule-request':
      case 'approved-reschedule':
      case 'rejected-reschedule':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      case 'new-order':
      case 'order-paid':
      case 'failed-payment':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      case 'fastboat-order-confirmation':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      case 'activity-order-confirmation':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      case 'tour-package-order-confirmation':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      case 'withdrawal-request':
      case 'withdrawal-cancelled':
        markAsRead({
          id: notification.id,
          merchantId,
        })

        router.push(getActionDetailLink(notification))

      default:
        break
    }
  }

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

  const value: NotificationContextType = {
    unreadCount,
    isLoading,
    refreshTrigger,
    readNotificationId,
    deletedNotificationId,
    setReadNotificationId,
    setDeletedNotificationId,
    setRefreshTrigger,
    setMerchantId,
    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>
  )
}
