package com.devlab.app.worker

import android.content.Context
import android.util.Log
import androidx.work.*
import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.AppNotification
import com.devlab.app.util.NotificationHelper
import com.devlab.app.util.PreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit

class NotificationWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {

    override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
        try {
            val prefs = PreferencesManager(applicationContext)
            val token = prefs.getToken()

            if (token.isBlank()) {
                Log.d("NotificationWorker", "No token, skipping")
                return@withContext Result.success()
            }

            val lastCheck = prefs.getLastNotificationCheck()
            val now = System.currentTimeMillis()

            Log.d("NotificationWorker", "Checking notifications since $lastCheck")

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

            try {
                val response = service.getNotifications(page = 1, perPage = 50)
                if (response.success) {
                    Log.d("NotificationWorker", "Got ${response.data.size} notifications, unread: ${response.unread_count}")

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

                    Log.d("NotificationWorker", "New notifications to show: ${newNotifications.size}")

                    for (notification in newNotifications) {
                        NotificationHelper.showNotification(applicationContext, notification)
                    }

                    val maxTime = newNotifications.maxOfOrNull {
                        parseTime(it.created_at)
                    } ?: now

                    prefs.setLastNotificationCheck(
                        if (newNotifications.isNotEmpty()) maxTime else now
                    )
                } else {
                    Log.d("NotificationWorker", "API returned success=false: ${response.error}")
                }
            } catch (e: Exception) {
                Log.e("NotificationWorker", "API error: ${e.message}")
            }

            Result.success()
        } catch (e: Exception) {
            Log.e("NotificationWorker", "Worker error: ${e.message}")
            Result.retry()
        }
    }

    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
        }
    }

    companion object {
        private const val WORK_NAME = "notification_check"

        fun schedule(context: Context) {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()

            val request = PeriodicWorkRequestBuilder<NotificationWorker>(
                15, TimeUnit.MINUTES
            )
                .setConstraints(constraints)
                .setBackoffCriteria(
                    BackoffPolicy.EXPONENTIAL,
                    1, TimeUnit.MINUTES
                )
                .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                WORK_NAME,
                ExistingPeriodicWorkPolicy.UPDATE,
                request
            )
            Log.d("NotificationWorker", "Scheduled periodic check every 15 min")
        }

        fun checkNow(context: Context) {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()

            val request = OneTimeWorkRequestBuilder<NotificationWorker>()
                .setConstraints(constraints)
                .build()

            WorkManager.getInstance(context).enqueue(request)
            Log.d("NotificationWorker", "Scheduled immediate check")
        }
    }
}
