package com.crm.chat.ui.chat

import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.crm.chat.R
import com.crm.chat.databinding.ActivityChatBinding
import com.crm.chat.utils.NotificationHelper

class ChatActivity : AppCompatActivity() {

    private lateinit var binding: ActivityChatBinding
    private val viewModel: ChatViewModel by viewModels()
    private lateinit var messageAdapter: MessageAdapter

    // Access to shared main view model for user data
    private val mainViewModel: com.crm.chat.ui.main.MainViewModel = com.crm.chat.ui.main.MainViewModel.getInstance()

    // Store chat users for message adapter
    private var chatUsers: List<com.crm.chat.data.model.ChatUserItem>? = null

    // Track loading states
    private var isChatLoaded = false
    private var areMessagesLoaded = false
    private var shouldScrollAfterRefresh = false

    // Reply functionality
    private var replyingToMessage: com.crm.chat.data.model.ChatMessage? = null
    private var isEditingMessage: Boolean = false

    // File attachment functionality
    private var selectedFileUri: android.net.Uri? = null
    private var selectedFileName: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChatBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val chatId = intent.getLongExtra("chat_id", -1)
        if (chatId == -1L) {
            finish()
            return
        }

        // Get auth data
        val prefs: SharedPreferences = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        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()) {
            finish()
            return
        }

        // Initialize main view model first
        // mainViewModel is already initialized as a property

        viewModel.initialize(serverUrl, token, apiKey, chatId)
        // Notification callback removed - notifications are handled by BackgroundSyncWorker
        // viewModel.notificationCallback = { message -> showNotification(message) }
        // Don't call refreshMessages() immediately - let initial load complete first
        setupViews()
        observeViewModel()
        observeAddressBook()
    }

    private fun setupViews() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false) // Hide default title
        supportActionBar?.setDisplayHomeAsUpEnabled(false) // We'll handle back button in custom view

        // Inflate custom toolbar view
        val customToolbarView = layoutInflater.inflate(R.layout.toolbar_chat, binding.toolbar, false)
        binding.toolbar.addView(customToolbarView)

        // Setup back button
        val backButton = customToolbarView.findViewById<android.widget.ImageButton>(R.id.backButton)
        backButton.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        // Setup chat name click handler
        val chatNameTextView = customToolbarView.findViewById<android.widget.TextView>(R.id.chatNameTextView)
        chatNameTextView.setOnClickListener {
            handleChatNameClick()
        }

        // Setup RecyclerView - adapter will be set when chat data is loaded
        binding.messagesRecyclerView.layoutManager = LinearLayoutManager(this@ChatActivity).apply {
            stackFromEnd = true
        }

        // Add scroll listener to mark messages as read when scrolling to bottom and control FAB visibility
        binding.messagesRecyclerView.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                checkAndMarkMessagesAsRead()
                updateScrollToBottomFabVisibility()
            }
        })

        // Setup send button
        binding.sendButton.setOnClickListener {
            val message = binding.messageEditText.text.toString().trim()

            // Check if we're editing a message
            if (isEditingMessage && replyingToMessage != null) {
                if (message.isNotEmpty()) {
                    // Edit the message
                    viewModel.editMessage(replyingToMessage!!.id, message)
                    binding.messageEditText.text?.clear()
                    // Clear edit state after editing
                    cancelReply()
                } else {
                    Toast.makeText(this, "Пожалуйста, введите сообщение", Toast.LENGTH_SHORT).show()
                }
                return@setOnClickListener
            }

            // Check if we have text, file, or both
            when {
                message.isNotEmpty() && selectedFileUri != null -> {
                    // Upload file first, then send message with both text and file
                    uploadFileAndSendMessage(message)
                }
                message.isNotEmpty() -> {
                    // Send text-only message (with reply if replying)
                    viewModel.sendMessage(message, replyingToMessage)
                    binding.messageEditText.text?.clear()
                    // Clear reply state after sending
                    cancelReply()
                }
                selectedFileUri != null -> {
                    // Send file-only message (with reply if replying)
                    viewModel.sendFileMessage(selectedFileUri!!, contentResolver)
                    // Clear file selection after sending
                    clearFileSelection()
                }
                else -> {
                    // No content to send
                    Toast.makeText(this, "Пожалуйста, введите сообщение или выберите файл", Toast.LENGTH_SHORT).show()
                }
            }
        }

        // Setup reply cancel button
        binding.replyCancelButton.setOnClickListener {
            cancelReply()
        }

        // Setup file attachment cancel button
        binding.fileCancelButton.setOnClickListener {
            clearFileSelection()
        }

        // Setup attach file button
        binding.attachButton.setOnClickListener {
            openFilePicker()
        }

        // Setup scroll to bottom FAB
        binding.scrollToBottomFab.setOnClickListener {
            scrollToBottom()
        }
    }

    private fun setupMessageAdapter() {
        // Get API credentials from preferences
        val prefs: SharedPreferences = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        val serverUrl = prefs.getString("server_url", null)
        val apiKey = prefs.getString("api_key", null)
        val token = prefs.getString("auth_token", null)
        val currentUserId = prefs.getLong("user_id", 12033923L) // Get current user ID from preferences

        messageAdapter = MessageAdapter(
            getUserName = { userId -> mainViewModel.getUserName(userId) },
            chatUsers = chatUsers,
            onScrollToMessage = { messageId -> scrollToMessage(messageId) },
            onReplyToMessage = { message -> startReplyToMessage(message) },
            onEditMessage = { message -> startEditMessage(message) },
            onDeleteMessage = { message -> deleteMessage(message) },
            onAddReaction = { message, emoji -> addReaction(message, emoji) },
            onRemoveReaction = { message, reactionId -> removeReaction(message, reactionId) },
            onReactionAdded = { 
                // Force refresh messages after reaction is added
                shouldScrollAfterRefresh = true
                viewModel.refreshMessages()
            },
            serverUrl = serverUrl,
            token = token,
            apiKey = apiKey,
            currentUserId = currentUserId
        )
        binding.messagesRecyclerView.adapter = messageAdapter
    }

    private fun observeViewModel() {
        viewModel.chatState.observe(this) { state ->
            when (state) {
                is com.crm.chat.ui.chat.ChatState.Loading -> {
                    isChatLoaded = false
                    updateLoadingState()
                }
                is com.crm.chat.ui.chat.ChatState.Success -> {
                    isChatLoaded = true

                    // Store chat users for message adapter
                    chatUsers = state.chat.users

                    // Setup message adapter now that we have chat data
                    setupMessageAdapter()

                    // Set chat name and avatar in custom toolbar
                    val chatName = when {
                        state.chat.title != null -> state.chat.title
                        state.chat.type == "personal" && state.chat.users != null && state.chat.users.size >= 2 -> {
                            // For personal chats, show the other user's name (same as chat list)
                            val currentUserId = 12033923L // Hardcoded for demo, should be from auth
                            val otherUser = state.chat.users?.find { it.userId != currentUserId }
                            otherUser?.let { user ->
                                // First try cached user data from address book
                                val cachedName = mainViewModel.getUserName(user.userId)
                                if (cachedName != "User ${user.userId}") {
                                    cachedName
                                } else {
                                    // Fallback to name from chat data, format as Last Name First Name
                                    user.name?.let { name ->
                                        // Assume name is "First Last", split and rearrange to "Last First"
                                        val parts = name.trim().split(" ")
                                        if (parts.size >= 2) {
                                            "${parts[1]} ${parts[0]}"
                                        } else {
                                            name
                                        }
                                    } ?: "Personal Chat"
                                }
                            } ?: "Personal Chat"
                        }
                        state.chat.type == "personal" -> "Личный чат"
                        else -> "Чат ${state.chat.id}"
                    }

                    // Set name in custom toolbar
                    val customToolbarView = binding.toolbar.getChildAt(0)
                    val chatNameTextView = customToolbarView.findViewById<android.widget.TextView>(R.id.chatNameTextView)
                    chatNameTextView.text = chatName

                    // Load avatar for personal chats
                    if (state.chat.type == "personal" && state.chat.users != null && state.chat.users.size >= 2) {
                        val currentUserId = 12033923L // Should be from auth store
                        val otherUser = state.chat.users.find { it.userId != currentUserId }

                        if (otherUser != null) {
                            loadChatAvatar(otherUser.userId, customToolbarView)
                        }
                    } else {
                        // For group chats or other types, use group chat icon
                        val chatAvatarImageView = customToolbarView.findViewById<android.widget.ImageView>(R.id.chatAvatarImageView)
                        chatAvatarImageView.setImageResource(R.drawable.ic_group_chat)
                    }

                    updateLoadingState()
                }
                is com.crm.chat.ui.chat.ChatState.Error -> {
                    isChatLoaded = false
                    updateLoadingState()
                    Toast.makeText(this, state.message, Toast.LENGTH_SHORT).show()
                }
            }
        }

        viewModel.messagesState.observe(this) { state ->
            when (state) {
                is MessagesState.Success -> {
                    areMessagesLoaded = true

                    // Only update if messageAdapter is initialized
                    if (::messageAdapter.isInitialized) {
                        // Check if user is currently at the bottom before updating
                        val layoutManager = binding.messagesRecyclerView.layoutManager as LinearLayoutManager
                        val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                        val totalItemCount = messageAdapter.itemCount
                        val isAtBottom = lastVisibleItemPosition >= totalItemCount - 1 // User is at or near the bottom

                        messageAdapter.submitList(state.messages)

                        // Handle scrolling logic
                        if (shouldScrollAfterRefresh) {
                            // Scroll to bottom after sending a message
                            shouldScrollAfterRefresh = false
                            // Use post to ensure layout is complete before scrolling
                            binding.messagesRecyclerView.post {
                                scrollToBottom()
                            }
                        } else if (isAtBottom) {
                            // Only auto-scroll to bottom if user was already at the bottom (for regular updates)
                            binding.messagesRecyclerView.post {
                                binding.messagesRecyclerView.scrollToPosition(state.messages.size - 1)
                                // Mark messages as read when opening chat and user is at bottom
                                viewModel.markMessagesAsRead()
                            }
                        }
                    }

                    updateLoadingState()
                }
                else -> {
                    areMessagesLoaded = false
                    updateLoadingState()
                }
            }
        }

        viewModel.sendMessageState.observe(this) { state ->
            when (state) {
                is SendMessageState.Success -> {
                    // Message sent successfully - notify main view model to refresh chat list
                    mainViewModel.notifyChatUpdated(intent.getLongExtra("chat_id", -1))

                    // Refresh messages to show the new message in the chat
                    shouldScrollAfterRefresh = true
                    viewModel.refreshMessages()
                }
                is SendMessageState.Error -> {
                    Toast.makeText(this, "Не удалось отправить сообщение: ${state.message}", Toast.LENGTH_SHORT).show()
                }
                else -> {} // Handle other states if needed
            }
        }

        viewModel.editMessageState.observe(this) { state ->
            when (state) {
                is EditMessageState.Success -> {
                    // Message edited successfully
                    Toast.makeText(this, "Сообщение отредактировано", Toast.LENGTH_SHORT).show()
                    // Messages are already refreshed by ViewModel
                }
                is EditMessageState.Error -> {
                    Toast.makeText(this, "Не удалось отредактировать сообщение: ${state.message}", Toast.LENGTH_SHORT).show()
                }
                else -> {} // Handle loading state if needed
            }
        }

        viewModel.deleteMessageState.observe(this) { state ->
            when (state) {
                is DeleteMessageState.Success -> {
                    // Message deleted successfully
                    Toast.makeText(this, "Сообщение удалено", Toast.LENGTH_SHORT).show()
                    // Messages are already refreshed by ViewModel
                }
                is DeleteMessageState.Error -> {
                    Toast.makeText(this, "Не удалось удалить сообщение: ${state.message}", Toast.LENGTH_SHORT).show()
                }
                else -> {} // Handle loading state if needed
            }
        }
    }

    private fun loadChatAvatar(userId: Long, customToolbarView: android.view.View) {
        val avatarUrl = mainViewModel.getUserAvatarUrl(userId)
        val userName = mainViewModel.getUserName(userId)
        val chatAvatarImageView = customToolbarView.findViewById<android.widget.ImageView>(R.id.chatAvatarImageView)

        if (avatarUrl != null && avatarUrl.isNotEmpty()) {
            // Load actual avatar image from URL with Glide
            Glide.with(this)
                .load(avatarUrl)
                .circleCrop()
                .placeholder(getUserColor(userId)) // Show color while loading
                .error(object : com.bumptech.glide.request.target.CustomTarget<android.graphics.drawable.Drawable>() {
                    override fun onResourceReady(resource: android.graphics.drawable.Drawable, transition: com.bumptech.glide.request.transition.Transition<in android.graphics.drawable.Drawable>?) {
                        // Avatar loaded successfully
                        chatAvatarImageView.setImageDrawable(resource)
                    }

                    override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {
                        // Show initials when avatar fails to load
                        showInitialsAvatar(userId, userName, chatAvatarImageView)
                    }
                })
                .into(chatAvatarImageView)

            print("Loading toolbar avatar for $userName: $avatarUrl")
        } else {
            // No avatar URL, show initials
            showInitialsAvatar(userId, userName, chatAvatarImageView)
            print("No toolbar avatar for $userName, showing initials")
        }
    }

    private fun showInitialsAvatar(userId: Long, userName: String, imageView: android.widget.ImageView) {
        // Generate initials from user name
        val initials = userName.split(" ").let { parts ->
            when (parts.size) {
                1 -> parts[0].take(1).uppercase()
                2 -> "${parts[0].take(1)}${parts[1].take(1)}".uppercase()
                else -> parts.firstOrNull()?.take(1)?.uppercase() ?: "U"
            }
        }

        // Background color for the avatar
        val backgroundColor = getUserColor(userId)

        // Create circular bitmap with initials
        val size = 192
        val bitmap = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)
        val canvas = android.graphics.Canvas(bitmap)

        // Draw circle background
        val circlePaint = android.graphics.Paint().apply {
            color = backgroundColor
            isAntiAlias = true
            style = android.graphics.Paint.Style.FILL
        }
        canvas.drawCircle(size / 2f, size / 2f, size / 2f, circlePaint)

        // Draw initials text
        val textPaint = android.graphics.Paint().apply {
            color = android.graphics.Color.WHITE
            textSize = size * 0.5f // Larger text for better visibility
            textAlign = android.graphics.Paint.Align.CENTER
            isAntiAlias = true
            typeface = android.graphics.Typeface.DEFAULT_BOLD
        }

        val xPos = size / 2f
        val yPos = size / 2f - (textPaint.descent() + textPaint.ascent()) / 2f
        canvas.drawText(initials, xPos, yPos, textPaint)

        // Clear any background color from ImageView (let the bitmap be fully circular)
        imageView.setBackgroundColor(android.graphics.Color.TRANSPARENT)
        imageView.setImageBitmap(bitmap)
    }

    private fun getUserColor(userId: Long): Int {
        // Generate a color based on user ID for consistency
        val colors = intArrayOf(
            "#E53935".toColorInt(), // Red
            "#1E88E5".toColorInt(), // Blue
            "#43A047".toColorInt(), // Green
            "#FB8C00".toColorInt(), // Orange
            "#8E24AA".toColorInt(), // Purple
            "#00ACC1".toColorInt(), // Cyan
            "#FDD835".toColorInt(), // Yellow
            "#6D4C41".toColorInt(), // Brown
        )
        return colors[(userId % colors.size).toInt()]
    }

    private fun observeAddressBook() {
        // Refresh message display when address book loads
        mainViewModel.addressBookState.observe(this) { state ->
            when (state) {
                is com.crm.chat.ui.main.MainViewModel.AddressBookState.Success -> {
                    // Address book loaded, refresh message display to show proper names
                    if (::messageAdapter.isInitialized) {
                        messageAdapter.notifyDataSetChanged()
                        println("DEBUG: Address book loaded, refreshing messages")
                    }
                }
                else -> {} // Handle other states if needed
            }
        }
    }

    private fun scrollToMessage(messageId: Long) {
        // Find the position of the message with the given ID
        val messages = messageAdapter.currentList
        val position = messages.indexOfFirst { it.id == messageId }

        if (position >= 0) {
            // Scroll to the message position
            binding.messagesRecyclerView.smoothScrollToPosition(position)

            // Optional: Highlight the message temporarily
            // You could add a highlight animation here if desired
        } else {
            // Message not found in current list
            Toast.makeText(this, "Сообщение не найдено", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startReplyToMessage(message: com.crm.chat.data.model.ChatMessage) {
        replyingToMessage = message
        isEditingMessage = false // We're replying, not editing

        // Show reply indicator above input field
        binding.replyIndicator.visibility = android.view.View.VISIBLE

        // Set reply sender name and message text
        val senderName = getUserNameFromChatUsers(message.chatUserId)
        binding.replySenderText.text = senderName
        binding.replyMessageText.text = message.text

        // Focus on input field
        binding.messageEditText.requestFocus()
    }

    private fun getUserNameFromChatUsers(chatUserId: Long): String {
        // Get user name from chat users data, similar to MessageAdapter logic
        val chatUserItem = chatUsers?.find { it.id == chatUserId }
        val actualUserId = chatUserItem?.userId ?: chatUserId

        // If this is the current user, show "Я" instead of their name
        val currentUserId = 12033923L // Hardcoded for demo, should be from auth
        if (actualUserId == currentUserId) {
            return "Я"
        }

        // Try to get name from chat user data first
        val nameFromChatUser = chatUserItem?.name
        if (!nameFromChatUser.isNullOrBlank()) {
            return formatNameForReply(nameFromChatUser)
        }

        // Fallback to main view model
        val nameFromViewModel = mainViewModel.getUserName(actualUserId)
        if (nameFromViewModel != "User $actualUserId") {
            return formatNameForReply(nameFromViewModel)
        }

        // Final fallback
        return "User $actualUserId"
    }

    private fun formatNameForReply(name: String): String {
        // Format name as "Last Name First Name" for replies
        val parts = name.trim().split(" ")
        return if (parts.size >= 2) {
            "${parts[1]} ${parts[0]}"
        } else {
            name
        }
    }

    private fun cancelReply() {
        replyingToMessage = null
        isEditingMessage = false
        binding.replyIndicator.visibility = android.view.View.GONE
    }

    private fun startEditMessage(message: com.crm.chat.data.model.ChatMessage) {
        // Set the message text in the input field
        binding.messageEditText.setText(message.text)

        // Store the message being edited and set editing flag
        replyingToMessage = message
        isEditingMessage = true // We're editing, not replying

        // Show edit indicator above input field
        binding.replyIndicator.visibility = android.view.View.VISIBLE
        binding.replySenderText.text = "Редактирование"
        binding.replyMessageText.text = message.text

        // Focus on input field and move cursor to end
        binding.messageEditText.requestFocus()
        binding.messageEditText.setSelection(message.text.length)
    }

    private fun deleteMessage(message: com.crm.chat.data.model.ChatMessage) {
        viewModel.deleteMessage(message.id)
    }

    private fun addReaction(message: com.crm.chat.data.model.ChatMessage, emoji: String) {
        viewModel.addReaction(message.id, emoji)
    }

    private fun removeReaction(message: com.crm.chat.data.model.ChatMessage, reactionId: Long) {
        viewModel.removeReaction(message.id, reactionId)
    }

    private fun openFilePicker() {
        val intent = android.content.Intent(android.content.Intent.ACTION_GET_CONTENT).apply {
            type = "*/*" // Allow all file types
            addCategory(android.content.Intent.CATEGORY_OPENABLE)
        }
        try {
            startActivityForResult(android.content.Intent.createChooser(intent, "Выберите файл"), FILE_PICKER_REQUEST_CODE)
        } catch (e: android.content.ActivityNotFoundException) {
            Toast.makeText(this, "Файловый менеджер не найден", Toast.LENGTH_SHORT).show()
        }
    }

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

        if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
            data?.data?.let { uri ->
                handleFileSelection(uri)
            }
        }
    }

    private fun handleFileSelection(uri: android.net.Uri) {
        try {
            // Get file information
            val fileName = getFileName(uri)
            val fileSize = getFileSize(uri)

            // Store selected file temporarily
            selectedFileUri = uri
            selectedFileName = fileName

            // Show file attachment indicator
            updateFileAttachmentUI()

            // Show confirmation
            Toast.makeText(this, "Файл выбран: $fileName (${formatFileSize(fileSize)})", Toast.LENGTH_LONG).show()

        } catch (e: Exception) {
            Toast.makeText(this, "Ошибка выбора файла: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun updateFileAttachmentUI() {
        if (selectedFileUri != null && selectedFileName != null) {
            // Show file attachment indicator
            binding.fileAttachmentIndicator.visibility = android.view.View.VISIBLE
            binding.fileAttachmentText.text = "Отправка: $selectedFileName"
        } else {
            // Hide file attachment indicator
            binding.fileAttachmentIndicator.visibility = android.view.View.GONE
        }
    }

    private fun clearFileSelection() {
        selectedFileUri = null
        selectedFileName = null
        updateFileAttachmentUI()
    }

    private fun uploadFileAndSendMessage(message: String) {
        if (selectedFileUri == null) return

        // Show progress
        Toast.makeText(this, "Загрузка файла...", Toast.LENGTH_SHORT).show()

        // Upload file first
        lifecycleScope.launch {
            try {
                val uploadResult = com.crm.chat.data.repository.ChatRepository(
                    com.crm.chat.data.api.ApiClient(
                        getSharedPreferences("crm_chat_prefs", MODE_PRIVATE).getString("server_url", "") ?: "",
                        getSharedPreferences("crm_chat_prefs", MODE_PRIVATE).getString("api_key", ""),
                        getSharedPreferences("crm_chat_prefs", MODE_PRIVATE).getString("auth_token", "")
                    )
                ).uploadFile(selectedFileUri!!, contentResolver)

                uploadResult.fold(
                    onSuccess = { uploadedFiles ->
                        if (uploadedFiles.isNotEmpty()) {
                            val fileIds = uploadedFiles.map { it.id }
                            // Send message with both text and file IDs
                            viewModel.sendMessage(message, replyingToMessage, fileIds)
                            binding.messageEditText.text?.clear()
                            // Clear reply state and file selection after sending
                            cancelReply()
                            clearFileSelection()
                        } else {
                            Toast.makeText(this@ChatActivity, "Не удалось загрузить файл", Toast.LENGTH_SHORT).show()
                        }
                    },
                    onFailure = { exception ->
                        Toast.makeText(this@ChatActivity, "Ошибка загрузки файла: ${exception.message}", Toast.LENGTH_SHORT).show()
                    }
                )
            } catch (e: Exception) {
                Toast.makeText(this@ChatActivity, "Ошибка: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun getFileName(uri: android.net.Uri): String {
        var fileName = "Unknown"
        if (uri.scheme == "content") {
            contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
                    if (nameIndex >= 0) {
                        fileName = cursor.getString(nameIndex)
                    }
                }
            }
        } else if (uri.scheme == "file") {
            fileName = java.io.File(uri.path!!).name
        }
        return fileName
    }

    private fun getFileSize(uri: android.net.Uri): Long {
        var fileSize: Long = 0
        if (uri.scheme == "content") {
            contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val sizeIndex = cursor.getColumnIndex(android.provider.OpenableColumns.SIZE)
                    if (sizeIndex >= 0) {
                        fileSize = cursor.getLong(sizeIndex)
                    }
                }
            }
        } else if (uri.scheme == "file") {
            fileSize = java.io.File(uri.path!!).length()
        }
        return fileSize
    }

    private fun formatFileSize(size: Long): String {
        if (size < 1024) return "$size B"
        val kb = size / 1024.0
        if (kb < 1024) return "%.1f KB".format(kb)
        val mb = kb / 1024.0
        if (mb < 1024) return "%.1f MB".format(mb)
        val gb = mb / 1024.0
        return "%.1f GB".format(gb)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressedDispatcher.onBackPressed()
        return true
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            STORAGE_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    // Permission granted
                    android.widget.Toast.makeText(
                        this,
                        "Разрешение на хранение получено. Попробуйте скачать файл снова.",
                        android.widget.Toast.LENGTH_LONG
                    ).show()
                } else {
                    // Permission denied
                    android.widget.Toast.makeText(
                        this,
                        "Разрешение на хранение отклонено. Файлы будут сохранены в хранилище приложения.",
                        android.widget.Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.setChatActive(true)
    }

    override fun onPause() {
        super.onPause()
        viewModel.setChatActive(false)
    }

    private fun updateScrollToBottomFabVisibility() {
        // Show FAB when user is not at the bottom, hide when at bottom
        val layoutManager = binding.messagesRecyclerView.layoutManager as? LinearLayoutManager ?: return
        val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
        val totalItemCount = messageAdapter.itemCount

        val isAtBottom = lastVisibleItemPosition >= totalItemCount - 1

        binding.scrollToBottomFab.visibility = if (isAtBottom) {
            android.view.View.GONE
        } else {
            android.view.View.VISIBLE
        }
    }

    private fun scrollToBottom() {
        if (::messageAdapter.isInitialized) {
            // Use post to ensure the layout is updated
            binding.messagesRecyclerView.post {
                if (messageAdapter.itemCount > 0) {
                    // Scroll to the last position with a small offset to ensure it's fully visible
                    val layoutManager = binding.messagesRecyclerView.layoutManager as LinearLayoutManager
                    layoutManager.scrollToPositionWithOffset(messageAdapter.itemCount - 1, 0)

                    // Also try smooth scroll as a fallback
                    binding.messagesRecyclerView.smoothScrollToPosition(messageAdapter.itemCount - 1)
                }
            }
        }
    }

    private fun checkAndMarkMessagesAsRead() {
        // Check if user is at the bottom of the chat (last message is visible)
        val layoutManager = binding.messagesRecyclerView.layoutManager as? LinearLayoutManager ?: return
        val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
        val totalItemCount = messageAdapter.itemCount

        // Only mark as read when the very last message is visible
        val isAtBottom = lastVisibleItemPosition == totalItemCount - 1

            if (isAtBottom && totalItemCount > 0) {
                // Mark all messages in this chat as read
                viewModel.markMessagesAsRead()
                // Badge notification will be updated automatically by MainViewModel
            }
    }

    private fun updateLoadingState() {
        // Show loading screen until both chat data and messages are loaded
        val isFullyLoaded = isChatLoaded && areMessagesLoaded

        if (isFullyLoaded) {
            // Hide loading screen and show chat content
            binding.loadingProgressBar.visibility = android.view.View.GONE
            binding.messagesRecyclerView.visibility = android.view.View.VISIBLE
            binding.messageInputLayout.visibility = android.view.View.VISIBLE
            binding.toolbar.visibility = android.view.View.VISIBLE
        } else {
            // Show loading screen and hide chat content
            binding.loadingProgressBar.visibility = android.view.View.VISIBLE
            binding.messagesRecyclerView.visibility = android.view.View.GONE
            binding.messageInputLayout.visibility = android.view.View.GONE
            binding.toolbar.visibility = android.view.View.GONE
        }
    }

    private fun handleChatNameClick() {
        // Get chat data to determine if it's personal or group
        val chatId = intent.getLongExtra("chat_id", -1)
        if (chatId == -1L) {
            Toast.makeText(this, "Ошибка: не удалось получить ID чата", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            try {
                // Get current chats from main view model
                val chats = mainViewModel.chatsState.value
                if (chats is com.crm.chat.ui.main.MainViewModel.ChatsState.Success) {
                    val chat = chats.chats.find { it.id == chatId }
                    if (chat != null) {
                        if (chat.type == "personal" && chat.users != null && chat.users.size >= 2) {
                            // Personal chat - open profile of the other user
                            val currentUserId = 12033923L // Should be from auth store
                            val otherUser = chat.users.find { it.userId != currentUserId }
                            
                            if (otherUser != null) {
                                val intent = android.content.Intent(this@ChatActivity, com.crm.chat.ui.profile.ProfileActivity::class.java)
                                intent.putExtra("user_id", otherUser.userId)
                                startActivity(intent)
                            }
                        } else {
                            // Group chat - open group info
                            val intent = android.content.Intent(this@ChatActivity, GroupChatInfoActivity::class.java)
                            intent.putExtra("chat_id", chatId)
                            startActivity(intent)
                        }
                    } else {
                        Toast.makeText(this@ChatActivity, "Чат не найден", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(this@ChatActivity, "Ошибка загрузки данных чата", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@ChatActivity, "Ошибка: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        private const val FILE_PICKER_REQUEST_CODE = 1001
        private const val STORAGE_PERMISSION_REQUEST_CODE = 2001
    }
}
