package com.crm.chat.ui.chat

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.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.crm.chat.R
import com.crm.chat.databinding.ActivityGroupChatInfoBinding
import com.crm.chat.ui.main.MainViewModel
import kotlinx.coroutines.launch
import com.bumptech.glide.Glide

class GroupChatInfoActivity : AppCompatActivity() {

    private lateinit var binding: ActivityGroupChatInfoBinding
    private val mainViewModel: MainViewModel = MainViewModel.getInstance()
    private lateinit var memberAdapter: GroupMemberAdapter

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

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

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

        setupRecyclerView()
        loadChatInfo(chatId)
    }

    private fun setupRecyclerView() {
        memberAdapter = GroupMemberAdapter { userId ->
            // Open profile for the clicked user
            val intent = Intent(this, com.crm.chat.ui.profile.ProfileActivity::class.java)
            intent.putExtra("user_id", userId)
            startActivity(intent)
        }
        binding.membersRecyclerView.layoutManager = LinearLayoutManager(this)
        binding.membersRecyclerView.adapter = memberAdapter
    }

    private fun loadChatInfo(chatId: Long) {
        binding.loadingProgressBar.visibility = android.view.View.VISIBLE

        lifecycleScope.launch {
            try {
                // Get chat data 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) {
                        // Set toolbar title and subtitle
                        supportActionBar?.title = chat.title ?: "Групповой чат"
                        val memberCount = chat.users?.size ?: 0
                        supportActionBar?.subtitle = "${memberCount} участников"

                        // Load members
                        val users = chat.users ?: emptyList()
                        memberAdapter.submitList(users)
                    } else {
                        Toast.makeText(this@GroupChatInfoActivity, "Чат не найден", Toast.LENGTH_SHORT).show()
                        finish()
                    }
                } else {
                    Toast.makeText(this@GroupChatInfoActivity, "Ошибка загрузки данных чата", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                Toast.makeText(this@GroupChatInfoActivity, "Ошибка загрузки информации: ${e.message}", Toast.LENGTH_SHORT).show()
                finish()
            } finally {
                binding.loadingProgressBar.visibility = android.view.View.GONE
            }
        }
    }



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