import { getToken } from '@/config/func'
import { useSocket } from '@/pages/pager/hooks/useSocket'
import { type FC, useEffect, useCallback, useState } from 'react'
import type { NotificationPayload } from '@/types/notification.types'
import { NotificationSubject } from '@/types/notification.types'
import NotificationItem from '@/components/NotificationItem'
import { useQueryClient } from '@tanstack/react-query'

interface NotificationItemData extends NotificationPayload {
    id: string
    timestamp: number
}

const Notification: FC = () => {
    const [notifications, setNotifications] = useState<NotificationItemData[]>([])
    const [audioEnabled, setAudioEnabled] = useState(false)
    const queryClient = useQueryClient()

    const token = getToken()
    const socketUrl = `${import.meta.env.VITE_SOCKET_URL}/notifications`
    const { connect, socket, error } = useSocket(socketUrl, token!)

    useEffect(() => {
        if (error) {
            console.error('❌ Notification: خطا در اتصال:', error)
        }
    }, [error])

    useEffect(() => {
        connect()
    }, [connect])

    useEffect(() => {
        const enableAudio = async () => {
            try {
                const audio = new Audio('/mixkit-correct-answer-tone-2870.wav')
                audio.volume = 0
                await audio.play()
                audio.pause()
                audio.currentTime = 0
                setAudioEnabled(true)
            } catch {
                console.warn('صدا هنوز فعال نشده است')
            }
        }

        const handleUserInteraction = () => {
            if (!audioEnabled) {
                enableAudio()
            }
        }

        window.addEventListener('click', handleUserInteraction, { once: true })
        window.addEventListener('touchstart', handleUserInteraction, { once: true })
        window.addEventListener('keydown', handleUserInteraction, { once: true })

        return () => {
            window.removeEventListener('click', handleUserInteraction)
            window.removeEventListener('touchstart', handleUserInteraction)
            window.removeEventListener('keydown', handleUserInteraction)
        }
    }, [audioEnabled])

    const handleGetNotification = useCallback((data: NotificationPayload) => {
        const newNotification: NotificationItemData = {
            ...data,
            id: `${Date.now()}-${Math.random()}`,
            timestamp: Date.now(),
        }
        setNotifications((prev) => [...prev, newNotification])

        // Refetch بر اساس نوع نوتیفیکیشن
        if (data.subject === NotificationSubject.PAGER_CREATED) {
            queryClient.invalidateQueries({ queryKey: ['pagers'] })
        } else if (data.subject === NotificationSubject.ORDER_CREATED) {
            queryClient.invalidateQueries({ queryKey: ['orders'] })
        }
    }, [queryClient])

    const handleRemoveNotification = useCallback((id: string) => {
        setNotifications((prev) => prev.filter((notif) => notif.id !== id))
    }, [])

    useEffect(() => {
        if (socket) {
            socket.on('joined', () => null)
            socket.on('notifications', handleGetNotification)

            return () => {
                socket.off('notifications', handleGetNotification)
            }
        }
    }, [socket, handleGetNotification])

    if (notifications.length === 0) {
        return null
    }

    return (
        <div className="fixed right-4 top-4 z-50 flex flex-col gap-2 max-w-[320px] w-full">
            {notifications.map((notification) => (
                <NotificationItem
                    key={notification.id}
                    id={notification.id}
                    subject={notification.subject}
                    body={notification.body}
                    onRemove={handleRemoveNotification}
                    audioEnabled={audioEnabled}
                />
            ))}
        </div>
    )
}

export default Notification
