package com.crm.chat.ui.main

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.recyclerview.widget.LinearLayoutManager
import com.crm.chat.R
import com.crm.chat.data.model.Chat
import com.crm.chat.databinding.ActivityMainBinding
import com.crm.chat.ui.auth.AuthActivity
import androidx.core.content.edit

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val viewModel: MainViewModel = MainViewModel.getInstance()
    private lateinit var chatAdapter: ChatAdapter
    private var currentChats: List<com.crm.chat.data.model.Chat> = emptyList()

    // Track if we're waiting for chat creation result
    private var isWaitingForChatCreation = false
    private var pendingUserIdForChatCreation: Long? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialize notification channel
        com.crm.chat.utils.NotificationHelper.createNotificationChannel(this)

        // Request notification permission on Android 13+
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            if (androidx.core.content.ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.POST_NOTIFICATIONS
                ) != android.content.pm.PackageManager.PERMISSION_GRANTED
            ) {
                androidx.core.app.ActivityCompat.requestPermissions(
                    this,
                    arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
                    NOTIFICATION_PERMISSION_REQUEST_CODE
                )
            }
        }

        // Apply saved theme preference
        val prefs: SharedPreferences = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        val savedThemeMode = prefs.getInt("theme_mode", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
        AppCompatDelegate.setDefaultNightMode(savedThemeMode)

        // Check if opened from notification
        val openChatId = intent.getLongExtra("open_chat_id", -1)
        if (openChatId != -1L) {
            openChatFromNotification(openChatId)
        }

        // Check if user is authenticated
        val token = prefs.getString("auth_token", null)
        val serverUrl = prefs.getString("server_url", null)
        val apiKey = prefs.getString("api_key", null)

        if (token.isNullOrEmpty() || serverUrl.isNullOrEmpty() || apiKey.isNullOrEmpty()) {
            // Not authenticated, go back to auth
            val intent = Intent(this, AuthActivity::class.java)
            startActivity(intent)
            finish()
            return
        }

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Initialize chat functionality (this will start polling)
        viewModel.initialize(this, serverUrl, token, apiKey)
        // Set badge update callback
        viewModel.badgeUpdateCallback = { unreadCount, senderName, latestMessage, userAvatar ->
            com.crm.chat.utils.NotificationHelper.updateAppIconBadge(this, unreadCount, senderName, latestMessage, userAvatar)
        }

        // Schedule background sync for when app is not running
        com.crm.chat.worker.BackgroundSyncManager.scheduleBackgroundSync(this)

        setupViews()
        observeViewModel()

        // Setup menu button click listener
        binding.menuButton.setOnClickListener {
            showPopupMenu()
        }

        // Initial refresh to ensure we have latest data
        viewModel.refreshChats()
    }

    override fun onResume() {
        super.onResume()
        // Immediately refresh chats when returning to foreground
        viewModel.refreshChats()
        // Ensure polling is active
        viewModel.ensurePollingIsActive()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_USER_SELECTION && resultCode == RESULT_OK && data != null) {
            val chatType = data.getStringExtra("chat_type")
            when (chatType) {
                "personal" -> {
                    val userId = data.getLongExtra("selected_user_id", -1)
                    val userName = data.getStringExtra("selected_user_name")
                    if (userId != -1L) {
                        createPersonalChat(userId, userName)
                    }
                }
                "group" -> {
                    val userIds = data.getLongArrayExtra("selected_user_ids")
                    val userNames = data.getStringArrayExtra("selected_user_names")
                    if (userIds != null && userIds.isNotEmpty() && userNames != null && userNames.isNotEmpty()) {
                        openCreateChatWithUsers(userIds, userNames)
                    }
                }
            }
        }
    }

    private fun setupViews() {
        // Setup toolbar
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        // Setup RecyclerView
        chatAdapter = ChatAdapter(
            onChatClick = { chat ->
                openChat(chat)
            },
            getUserName = { userId ->
                viewModel.getUserName(userId)
            },
            getUserAvatarUrl = { userId ->
                viewModel.getUserAvatarUrl(userId)
            }
        )

        binding.chatsRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = chatAdapter
        }

        // Add swipe-to-delete functionality
        val itemTouchHelper = androidx.recyclerview.widget.ItemTouchHelper(object : androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback(
            0, androidx.recyclerview.widget.ItemTouchHelper.LEFT or androidx.recyclerview.widget.ItemTouchHelper.RIGHT
        ) {
            override fun onMove(
                recyclerView: androidx.recyclerview.widget.RecyclerView,
                viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
                target: androidx.recyclerview.widget.RecyclerView.ViewHolder
            ): Boolean {
                return false // No drag and drop
            }

            override fun onSwiped(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                val chat = chatAdapter.currentList[position]
                showDeleteConfirmationDialog(chat)
            }

            override fun onChildDraw(
                c: android.graphics.Canvas,
                recyclerView: androidx.recyclerview.widget.RecyclerView,
                viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
                dX: Float,
                dY: Float,
                actionState: Int,
                isCurrentlyActive: Boolean
            ) {
                val itemView = viewHolder.itemView
                val icon = getDrawable(android.R.drawable.ic_delete)

                if (icon != null) {
                    val iconMargin = (itemView.height - icon.intrinsicHeight) / 2
                    val iconTop = itemView.top + (itemView.height - icon.intrinsicHeight) / 2
                    val iconBottom = iconTop + icon.intrinsicHeight

                    if (dX > 0) { // Swiping right
                        val iconLeft = itemView.left + iconMargin
                        val iconRight = itemView.left + iconMargin + icon.intrinsicWidth
                        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
                    } else { // Swiping left
                        val iconRight = itemView.right - iconMargin
                        val iconLeft = itemView.right - iconMargin - icon.intrinsicWidth
                        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
                    }

                    icon.draw(c)
                }

                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            }
        })

        itemTouchHelper.attachToRecyclerView(binding.chatsRecyclerView)

        // Setup swipe refresh
        binding.swipeRefreshLayout.setOnRefreshListener {
            viewModel.refreshChats()
        }

        // Setup retry button
        binding.retryButton.setOnClickListener {
            viewModel.refreshChats()
        }

    // Setup FAB for creating new chat
    binding.createChatFab.setOnClickListener {
        openUserSelection()
    }
    }

    private fun observeViewModel() {
        viewModel.chatsState.observe(this) { state ->
            binding.swipeRefreshLayout.isRefreshing = false

            when (state) {
                is MainViewModel.ChatsState.Loading -> {
                    // Only show loading if we're not waiting for chat creation
                    if (!isWaitingForChatCreation) {
                        showLoadingState()
                    }
                }
                is MainViewModel.ChatsState.Success -> {
                    if (state.chats.isEmpty()) {
                        showEmptyState()
                    } else {
                        showChats(state.chats)
                        // Load user names for personal chats
                        loadUserNamesForChats(state.chats)

                        // Handle chat creation result
                        handleChatCreationResult(state.chats)
                    }
                }
                is MainViewModel.ChatsState.Error -> {
                    // Handle chat creation error
                    if (isWaitingForChatCreation) {
                        Toast.makeText(this, "Ошибка создания чата: ${state.message}", Toast.LENGTH_LONG).show()
                        isWaitingForChatCreation = false
                        pendingUserIdForChatCreation = null
                    } else {
                        showErrorState(state.message)
                    }
                }
            }
        }

        // Observe address book state to refresh chat names when user data loads
        viewModel.addressBookState.observe(this) { state ->
            when (state) {
                is MainViewModel.AddressBookState.Success -> {
                    // User data has loaded, refresh the chat list to show proper names
                    if (viewModel.chatsState.value is MainViewModel.ChatsState.Success) {
                        chatAdapter.notifyDataSetChanged()
                    }
                }
                else -> {} // Handle other states if needed
            }
        }
    }

    private fun handleChatCreationResult(chats: List<com.crm.chat.data.model.Chat>) {
        if (isWaitingForChatCreation && pendingUserIdForChatCreation != null) {
            // Check if this is a new chat creation (look for recent chat with the user)
            val newChat = chats.find { chat ->
                chat.type == "personal" && chat.users?.any { it.userId == pendingUserIdForChatCreation } == true
            }
            if (newChat != null) {
                Toast.makeText(this, "Личный чат успешно создан", Toast.LENGTH_SHORT).show()
                openChat(newChat)
                // Reset flags
                isWaitingForChatCreation = false
                pendingUserIdForChatCreation = null
            }
        }
    }

    private fun loadUserNamesForChats(chats: List<Chat>) {
        // User names are now loaded from the address book cache
        // No need to load individual users since we have all user data
    }

    private fun showLoadingState() {
        binding.loadingProgressBar.visibility = android.view.View.VISIBLE
        binding.chatsRecyclerView.visibility = android.view.View.GONE
        binding.emptyStateLayout.visibility = android.view.View.GONE
        binding.errorStateLayout.visibility = android.view.View.GONE
    }

    private fun showChats(chats: List<Chat>) {
        binding.loadingProgressBar.visibility = android.view.View.GONE
        binding.chatsRecyclerView.visibility = android.view.View.VISIBLE
        binding.emptyStateLayout.visibility = android.view.View.GONE
        binding.errorStateLayout.visibility = android.view.View.GONE

        // Simply submit the list - DiffUtil will handle efficient updates
        currentChats = chats.toList()
        chatAdapter.submitList(currentChats)
    }

    private fun hasChatContentChanged(oldChat: Chat, newChat: Chat): Boolean {
        return oldChat.unseenCount != newChat.unseenCount ||
               oldChat.lastMessage?.id != newChat.lastMessage?.id ||
               oldChat.lastMessage?.text != newChat.lastMessage?.text ||
               oldChat.lastMessage?.createdAt != newChat.lastMessage?.createdAt
    }

    private fun showEmptyState() {
        binding.loadingProgressBar.visibility = android.view.View.GONE
        binding.chatsRecyclerView.visibility = android.view.View.GONE
        binding.emptyStateLayout.visibility = android.view.View.VISIBLE
        binding.errorStateLayout.visibility = android.view.View.GONE
    }

    private fun showErrorState(message: String) {
        binding.loadingProgressBar.visibility = android.view.View.GONE
        binding.chatsRecyclerView.visibility = android.view.View.GONE
        binding.emptyStateLayout.visibility = android.view.View.GONE
        binding.errorStateLayout.visibility = android.view.View.VISIBLE

        binding.errorTextView.text = message
    }

    private fun openChat(chat: Chat) {
        val intent = Intent(this, com.crm.chat.ui.chat.ChatActivity::class.java)
        intent.putExtra("chat_id", chat.id)
        startActivity(intent)
    }

    private fun openUserSelection() {
        val intent = Intent(this, UserSelectionActivity::class.java)
        startActivityForResult(intent, REQUEST_USER_SELECTION)
    }

    private fun openCreateChat() {
        val intent = Intent(this, CreateChatActivity::class.java)
        startActivity(intent)
    }



    private fun toggleTheme() {
        // Read current theme preference
        val prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        val currentMode = prefs.getInt("theme_mode", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)

        // Toggle between light and dark
        val newNightMode = when (currentMode) {
            AppCompatDelegate.MODE_NIGHT_YES -> AppCompatDelegate.MODE_NIGHT_NO
            else -> AppCompatDelegate.MODE_NIGHT_YES
        }

        // Apply new theme
        AppCompatDelegate.setDefaultNightMode(newNightMode)

        // Save the preference
        prefs.edit { putInt("theme_mode", newNightMode) }

        // Recreate activity to apply theme change immediately
        recreate()
    }

    private fun createPersonalChat(userId: Long, userName: String?) {
        // First check if chat already exists
        val existingChat = currentChats.find { chat ->
            chat.type == "personal" && chat.users?.any { it.userId == userId } == true
        }

        if (existingChat != null) {
            // Chat already exists, just open it
            Toast.makeText(this, "Открыт существующий чат", Toast.LENGTH_SHORT).show()
            openChat(existingChat)
            return
        }

        // Create personal chat directly using the API
        // Use provider ID from HAR file (994)
        viewModel.createPersonalChat(994L, userId)

        // Set flags to track chat creation
        isWaitingForChatCreation = true
        pendingUserIdForChatCreation = userId

        // Show loading state immediately
        showLoadingState()
    }

    private fun openCreateChatWithUsers(userIds: LongArray, userNames: Array<String>) {
        val intent = Intent(this, CreateChatActivity::class.java).apply {
            putExtra("selected_user_ids", userIds)
            putExtra("selected_user_names", userNames)
            putExtra("chat_type", "group")
        }
        startActivity(intent)
    }

    private fun showDeleteConfirmationDialog(chat: com.crm.chat.data.model.Chat) {
        val chatName = when (chat.type) {
            "personal" -> {
                val otherUser = chat.users?.find { it.userId != getCurrentUserId() }
                if (otherUser != null) {
                    viewModel.getUserName(otherUser.userId)
                } else {
                    "Личный чат"
                }
            }
            "group" -> chat.title ?: "Групповой чат"
            else -> chat.title ?: "Чат"
        }

        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("Удалить чат")
            .setMessage("Вы действительно хотите удалить чат \"$chatName\"? Это действие нельзя отменить.")
            .setPositiveButton("Удалить") { _, _ ->
                deleteChat(chat)
            }
            .setNegativeButton("Отмена") { dialog, _ ->
                dialog.dismiss()
                // Refresh the list to restore the swiped item
                chatAdapter.notifyDataSetChanged()
            }
            .setOnCancelListener {
                // Refresh the list to restore the swiped item
                chatAdapter.notifyDataSetChanged()
            }
            .show()
    }

    private fun deleteChat(chat: com.crm.chat.data.model.Chat) {
        viewModel.deleteChat(chat.id)
        Toast.makeText(this, "Чат удален", Toast.LENGTH_SHORT).show()
    }

    private fun getCurrentUserId(): Long {
        val prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        return prefs.getLong("current_user_id", 12033923L) // Default from HAR file
    }

    private fun showPopupMenu() {
        val popupMenu = androidx.appcompat.widget.PopupMenu(this, binding.menuButton)
        popupMenu.menuInflater.inflate(R.menu.main_menu, popupMenu.menu)
        popupMenu.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.menu_profile -> {
                    openProfile()
                    true
                }
                R.id.menu_settings -> {
                    openSettings()
                    true
                }
                R.id.menu_logout -> {
                    showLogoutConfirmation()
                    true
                }
                else -> false
            }
        }
        popupMenu.show()
    }

    private fun openProfile() {
        val intent = Intent(this, com.crm.chat.ui.profile.ProfileActivity::class.java)
        startActivity(intent)
    }

    private fun openSettings() {
        val intent = Intent(this, com.crm.chat.ui.settings.SettingsActivity::class.java)
        startActivity(intent)
    }

    private fun showLogoutConfirmation() {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("Выход")
            .setMessage("Вы действительно хотите выйти из аккаунта?")
            .setPositiveButton("Выйти") { _, _ ->
                logout()
            }
            .setNegativeButton("Отмена", null)
            .show()
    }

    private fun logout() {
        // Clear authentication data
        val prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        prefs.edit()
            .remove("auth_token")
            .remove("server_url")
            .remove("api_key")
            .remove("current_user_id")
            .apply()

        // Stop background sync
        com.crm.chat.worker.BackgroundSyncManager.cancelBackgroundSync(this)

        // Navigate back to auth activity
        val intent = Intent(this, AuthActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }

    private fun openChatFromNotification(chatId: Long) {
        // Wait for chats to load, then open the specific chat
        viewModel.chatsState.observe(this) { state ->
            if (state is MainViewModel.ChatsState.Success) {
                val chat = state.chats.find { it.id == chatId }
                if (chat != null) {
                    openChat(chat)
                    // Remove observer after opening
                    viewModel.chatsState.removeObservers(this)
                }
            }
        }
    }

    companion object {
        private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1001
        private const val REQUEST_USER_SELECTION = 1002
    }
}
