package com.devlab.app.util

import android.content.Context
import android.util.Log
import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.AppNotification
import kotlinx.coroutines.*

class NotificationPoller(private val context: Context) {

    private var job: Job? = null
    private var lastCheck: Long = 0
    private var _unreadCount: Int = 0
    val unreadCount: Int get() = _unreadCount
    var onCountChanged: ((Int) -> Unit)? = null

    companion object {
        private const val POLL_INTERVAL_MS = 30_000L
    }

    fun start() {
        if (job?.isActive == true) return
        lastCheck = System.currentTimeMillis()

        job = CoroutineScope(Dispatchers.IO).launch {
            while (isActive) {
                try {
                    checkNow()
                } catch (_: Exception) { }
                delay(POLL_INTERVAL_MS)
            }
        }
        Log.d("NotificationPoller", "Started polling every 30s")
    }

    fun stop() {
        job?.cancel()
        job = null
        Log.d("NotificationPoller", "Stopped")
    }

    fun checkNow() {
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            try {
                val prefs = PreferencesManager(context)
                val token = prefs.getToken()
                if (token.isBlank()) return@launch

                RetrofitClient.setToken(token)
                val service = RetrofitClient.getApiService()

                val response = service.getNotifications(page = 1, perPage = 5)
                if (response.success) {
                    _unreadCount = response.unread_count
                    onCountChanged?.invoke(_unreadCount)

                    val newNotes = response.data.filter { note ->
                        val noteTime = parseTime(note.created_at)
                        noteTime > lastCheck && note.is_read == 0
                    }

                    for (notification in newNotes) {
                        NotificationHelper.showNotification(context, notification)
                    }

                    if (newNotes.isNotEmpty()) {
                        lastCheck = newNotes.maxOf { parseTime(it.created_at) }
                    }
                }
            } catch (_: Exception) { }
        }
    }

    private fun parseTime(time: String?): Long {
        if (time == null) return 0L
        return try {
            val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US).apply {
                timeZone = java.util.TimeZone.getTimeZone("UTC")
            }
            sdf.parse(time)?.time ?: 0L
        } catch (_: Exception) { 0L }
    }
}
