package com.omixlab.lckcontrol.chat

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import com.omixlab.lckcontrol.R
import com.omixlab.lckcontrol.data.remote.ChatMessageEvent
import com.omixlab.lckcontrol.data.repository.ChatRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ChatNotificationManager @Inject constructor(
    @ApplicationContext private val context: Context,
    private val chatRepository: ChatRepository,
) {
    companion object {
        private const val CHANNEL_ID = "lck_chat_messages"
        private const val NOTIFICATION_TAG = "chat_msg"
    }

    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    private val notificationManager = context.getSystemService(NotificationManager::class.java)
    private var notificationIdCounter = 100
    private var appInForeground = true

    fun init() {
        createNotificationChannel()
        scope.launch {
            chatRepository.latestMessage.collect { event ->
                if (!appInForeground) {
                    showNotification(event)
                }
            }
        }
    }

    fun setAppForeground(foreground: Boolean) {
        appInForeground = foreground
    }

    private fun createNotificationChannel() {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Chat Messages",
            NotificationManager.IMPORTANCE_DEFAULT,
        ).apply {
            description = "Live chat messages from YouTube and Twitch"
        }
        notificationManager.createNotificationChannel(channel)
    }

    private fun showNotification(event: ChatMessageEvent) {
        val title = if (event.service == "YOUTUBE") "YouTube Chat" else "Twitch Chat"
        val body = "${event.message.authorName}: ${event.message.text}"

        val notification = android.app.Notification.Builder(context, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(NOTIFICATION_TAG, notificationIdCounter++, notification)
    }
}
