package com.crm.chat.worker

import android.content.Context
import android.content.SharedPreferences
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.crm.chat.data.api.ApiClient
import com.crm.chat.data.repository.ChatRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class BackgroundSyncWorker(
    appContext: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
        try {
            // Get stored credentials
            val prefs: SharedPreferences = applicationContext.getSharedPreferences("crm_chat_prefs", Context.MODE_PRIVATE)
            val token = prefs.getString("auth_token", null)
            val serverUrl = prefs.getString("server_url", null)
            val apiKey = prefs.getString("api_key", null)
            val currentUserId = prefs.getLong("current_user_id", 12033923L) // Default to hardcoded value

            if (token.isNullOrEmpty() || serverUrl.isNullOrEmpty() || apiKey.isNullOrEmpty()) {
                // Not authenticated, skip
                return@withContext Result.success()
            }

            // Create repository
            val apiClient = ApiClient(serverUrl, apiKey, token)
            val chatRepository = ChatRepository(apiClient)

            // Load chats first to get chat information
            val chatsResult = chatRepository.getChats()
            if (chatsResult.isFailure) {
                println("Background sync: Failed to load chats: ${chatsResult.exceptionOrNull()?.message}")
                return@withContext Result.retry()
            }

            val chats = chatsResult.getOrNull() ?: emptyList()
            println("Background sync: Loaded ${chats.size} chats")

            // Load address book (users) for name resolution
            val usersResult = chatRepository.getUsers(null)
            val users = usersResult.getOrNull() ?: emptyList()
            println("Background sync: Loaded ${users.size} users")
            if (users.isNotEmpty()) {
                println("Background sync: Sample user: ${users.first().id} - ${users.first().firstName} ${users.first().lastName}")
            }

            // Cache user avatars for faster notification display (only download if files don't match)
            println("DEBUG: BackgroundSyncWorker caching ${users.size} user avatars")
            users.forEach { user ->
                // Check if avatar needs to be downloaded (only if URL exists and file doesn't match)
                if (user.avatarUrl != null) {
                    val cacheFile = getAvatarCacheFile(applicationContext, user.id)
                    val needsDownload = !cacheFile.exists() || !isAvatarUpToDate(cacheFile, user.avatarUrl)

                    if (needsDownload) {
                        println("DEBUG: Downloading avatar for user ${user.id}")
                        com.crm.chat.utils.NotificationHelper.cacheUserAvatar(applicationContext, user)
                    } else {
                        println("DEBUG: Avatar already cached and up-to-date for user ${user.id}")
                    }
                }
            }

            // Check each chat for new messages
            var totalNewMessages = 0
            val chatsWithNewMessages = mutableListOf<Pair<com.crm.chat.data.model.Chat, List<com.crm.chat.data.model.ChatMessage>>>()

            for (chat in chats) {
                try {
                    // Get recent messages for this chat (last 10 messages)
                    val messagesResult = chatRepository.getChatMessages(chat.id, limit = 10)
                    if (messagesResult.isSuccess) {
                        val messagesResponse = messagesResult.getOrNull()
                        val messages = messagesResponse?.messages ?: emptyList()

                        // Filter messages that are not from current user and not already seen
                        val newMessages = messages.filter { message ->
                            val isFromOtherUser = message.chatUserId != currentUserId
                            val isNew = isMessageNew(message, chat.id, prefs)
                            isFromOtherUser && isNew
                        }

                        if (newMessages.isNotEmpty()) {
                            chatsWithNewMessages.add(chat to newMessages)
                            totalNewMessages += newMessages.size

                            // Mark these messages as notified to avoid duplicate notifications
                            markMessagesAsNotified(newMessages, chat.id, prefs)
                        }
                    }
                } catch (e: Exception) {
                    println("Background sync: Error checking chat ${chat.id}: ${e.message}")
                }
            }

            // Badge notifications are handled by MainViewModel when chats are loaded
            // No need to show individual notifications here

            println("Background sync: Found $totalNewMessages new messages across ${chatsWithNewMessages.size} chats")
            Result.success()
        } catch (e: Exception) {
            println("Background sync: Unexpected error: ${e.message}")
            Result.retry()
        }
    }

    private fun isMessageNew(message: com.crm.chat.data.model.ChatMessage, chatId: Long, prefs: SharedPreferences): Boolean {
        val lastNotifiedId = prefs.getLong("last_notified_message_${chatId}", 0)
        return message.id > lastNotifiedId
    }

    private fun markMessagesAsNotified(messages: List<com.crm.chat.data.model.ChatMessage>, chatId: Long, prefs: SharedPreferences) {
        val latestMessageId = messages.maxOfOrNull { it.id } ?: return
        prefs.edit().putLong("last_notified_message_${chatId}", latestMessageId).apply()
    }



    private fun getAvatarCacheFile(context: Context, userId: Long): java.io.File {
        val cacheDir = java.io.File(context.cacheDir, "user_avatars")
        if (!cacheDir.exists()) {
            cacheDir.mkdirs()
        }
        return java.io.File(cacheDir, "avatar_$userId.png")
    }

    private fun isAvatarUpToDate(cacheFile: java.io.File, avatarUrl: String): Boolean {
        // For now, we'll just check if the file exists
        // In a more sophisticated implementation, we could check file timestamps or ETags
        // But for simplicity, we'll assume cached avatars are up-to-date unless the URL changes
        return cacheFile.exists()
    }
}
