package com.crm.chat.ui.main

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import com.crm.chat.R
import com.crm.chat.data.model.*
import com.crm.chat.databinding.ActivityCreateChatBinding
import com.crm.chat.ui.chat.ChatActivity

class CreateChatActivity : AppCompatActivity() {

    private lateinit var binding: ActivityCreateChatBinding
    private val viewModel: MainViewModel = MainViewModel.getInstance()
    private var selectedUserId: Long? = null
    private var selectedUserName: String? = null
    private var selectedUserIds: LongArray? = null
    private var selectedUserNames: Array<String>? = null
    private var isCreatingChat = false

    companion object {
        private const val REQUEST_SELECT_USER = 1001
    }

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

        // Initialize with auth data
        val prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        val serverUrl = prefs.getString("server_url", "") ?: ""
        val token = prefs.getString("auth_token", "") ?: ""
        val apiKey = prefs.getString("api_key", "") ?: ""

        if (token.isNotEmpty() && serverUrl.isNotEmpty()) {
            viewModel.initialize(this, serverUrl, token, apiKey)
        }

        setupViews()
        observeViewModel()

        // Check if we received group chat data from intent (after views are set up)
        handleIntentData()
    }

    private fun handleIntentData() {
        val chatType = intent.getStringExtra("chat_type")
        if (chatType == "group") {
            selectedUserIds = intent.getLongArrayExtra("selected_user_ids")
            selectedUserNames = intent.getStringArrayExtra("selected_user_names")

            val userIds = selectedUserIds
            val userNames = selectedUserNames
            if (userIds != null && userIds.isNotEmpty() && userNames != null && userNames.isNotEmpty()) {
                // Hide chat type selection for pre-selected group chat
                binding.chatTypeLabel.visibility = View.GONE
                binding.chatTypeRadioGroup.visibility = View.GONE

                // Show group chat fields directly
                showGroupChatFields()
                binding.participantsEditText.setText(userIds.joinToString(", "))
                binding.participantsEditText.isEnabled = false // Make it read-only since users are pre-selected
                binding.groupTitleEditText.requestFocus() // Focus on group name input

                // Update title to indicate group chat creation
                binding.titleTextView.text = "Создать групповой чат"
            }
        }
    }

    private fun setupViews() {
        // Show personal chat fields by default
        showPersonalChatFields()

        // Chat type selection
        binding.chatTypeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.radioPersonal -> showPersonalChatFields()
                R.id.radioGroup -> showGroupChatFields()
                R.id.radioExternal -> showExternalChatFields()
            }
        }

        // Select user button click
        binding.selectUserButton.setOnClickListener {
            val intent = Intent(this, UserSelectionActivity::class.java)
            startActivityForResult(intent, REQUEST_SELECT_USER)
        }

        // Create button click
        binding.createButton.setOnClickListener {
            createChat()
        }

        // Clear error when user starts typing
        binding.groupTitleEditText.doOnTextChanged { _, _, _, _ ->
            binding.errorTextView.visibility = View.GONE
        }

        binding.participantsEditText.doOnTextChanged { _, _, _, _ ->
            binding.errorTextView.visibility = View.GONE
        }

        binding.externalTitleEditText.doOnTextChanged { _, _, _, _ ->
            binding.errorTextView.visibility = View.GONE
        }

        binding.entityEditText.doOnTextChanged { _, _, _, _ ->
            binding.errorTextView.visibility = View.GONE
        }
    }

    private fun showPersonalChatFields() {
        binding.companionLabel.visibility = View.VISIBLE
        binding.selectUserButton.visibility = View.VISIBLE
        binding.selectedUserTextView.visibility = View.VISIBLE

        binding.groupTitleLabel.visibility = View.GONE
        binding.groupTitleInputLayout.visibility = View.GONE
        binding.participantsLabel.visibility = View.GONE
        binding.participantsInputLayout.visibility = View.GONE

        binding.externalTitleLabel.visibility = View.GONE
        binding.externalTitleInputLayout.visibility = View.GONE
    }

    private fun showGroupChatFields() {
        binding.companionLabel.visibility = View.GONE
        binding.selectUserButton.visibility = View.GONE
        binding.selectedUserTextView.visibility = View.GONE

        binding.groupTitleLabel.visibility = View.VISIBLE
        binding.groupTitleInputLayout.visibility = View.VISIBLE
        binding.participantsLabel.visibility = View.GONE // Hide participant IDs for simplified UI
        binding.participantsInputLayout.visibility = View.GONE

        binding.externalTitleLabel.visibility = View.GONE
        binding.externalTitleInputLayout.visibility = View.GONE

        // For pre-selected group chats, hide entity ID as well
        if (selectedUserIds != null && selectedUserIds!!.isNotEmpty()) {
            binding.entityLabel.visibility = View.GONE
            binding.entityInputLayout.visibility = View.GONE
        }
    }

    private fun showExternalChatFields() {
        binding.companionLabel.visibility = View.GONE
        binding.selectUserButton.visibility = View.GONE
        binding.selectedUserTextView.visibility = View.GONE

        binding.groupTitleLabel.visibility = View.GONE
        binding.groupTitleInputLayout.visibility = View.GONE
        binding.participantsLabel.visibility = View.GONE
        binding.participantsInputLayout.visibility = View.GONE

        binding.externalTitleLabel.visibility = View.VISIBLE
        binding.externalTitleInputLayout.visibility = View.VISIBLE
    }

    private fun createChat() {
        // Check if this is a pre-selected group chat (radio group is hidden)
        if (selectedUserIds != null && selectedUserIds!!.isNotEmpty()) {
            createGroupChat()
            return
        }

        // Otherwise determine from radio button
        val chatType = when (binding.chatTypeRadioGroup.checkedRadioButtonId) {
            R.id.radioPersonal -> "personal"
            R.id.radioGroup -> "group"
            R.id.radioExternal -> "external"
            else -> "personal"
        }

        when (chatType) {
            "personal" -> createPersonalChat()
            "group" -> createGroupChat()
            "external" -> createExternalChat()
        }
    }

    private fun createPersonalChat() {
        val companionId = selectedUserId
        val entityIdText = binding.entityEditText.text?.toString()?.trim()

        if (companionId == null) {
            binding.errorTextView.text = "Выберите собеседника"
            binding.errorTextView.visibility = View.VISIBLE
            return
        }

        val entityId = entityIdText?.toLongOrNull()
        val providerId = 994L // From API logs

        isCreatingChat = true
        viewModel.createPersonalChat(providerId, companionId)
    }

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

        if (requestCode == REQUEST_SELECT_USER && resultCode == RESULT_OK) {
            selectedUserId = data?.getLongExtra("selected_user_id", -1)
            selectedUserName = data?.getStringExtra("selected_user_name")

            if (selectedUserId != null && selectedUserId != -1L) {
                binding.selectedUserTextView.text = "Выбран: $selectedUserName (ID: $selectedUserId)"
                binding.selectedUserTextView.visibility = View.VISIBLE
                binding.selectUserButton.text = "Изменить выбор"
            }
        }
    }

    private fun createGroupChat() {
        val title = binding.groupTitleEditText.text?.toString()?.trim()

        if (title.isNullOrBlank()) {
            binding.errorTextView.text = "Введите название группы"
            binding.errorTextView.visibility = View.VISIBLE
            return
        }

        // Use selectedUserIds if available (from user selection), otherwise parse from text field
        val participantIds = selectedUserIds?.toList() ?: run {
            val participantsText = binding.participantsEditText.text?.toString()?.trim()
            if (participantsText.isNullOrBlank()) {
                emptyList()
            } else {
                try {
                    participantsText.split(",").map { it.trim().toLong() }
                } catch (e: NumberFormatException) {
                    binding.errorTextView.text = "Некорректные ID участников"
                    binding.errorTextView.visibility = View.VISIBLE
                    return
                }
            }
        }

        if (participantIds.isEmpty()) {
            binding.errorTextView.text = "Не выбраны участники группы"
            binding.errorTextView.visibility = View.VISIBLE
            return
        }

        // For pre-selected group chats, don't use entityId (field is hidden)
        val entityId = if (selectedUserIds != null && selectedUserIds!!.isNotEmpty()) {
            null
        } else {
            binding.entityEditText.text?.toString()?.trim()?.toLongOrNull()
        }

        // Use provider ID from HAR file (994)
        val providerId = 994L

        isCreatingChat = true
        viewModel.createGroupChat(providerId, participantIds, title, entityId)
    }

    private fun createExternalChat() {
        val title = binding.externalTitleEditText.text?.toString()?.trim()
        val entityIdText = binding.entityEditText.text?.toString()?.trim()

        if (title.isNullOrBlank()) {
            binding.errorTextView.text = "Введите название чата"
            binding.errorTextView.visibility = View.VISIBLE
            return
        }

        val entityId = entityIdText?.toLongOrNull()

        isCreatingChat = true
        viewModel.createExternalChat(title, entityId)
    }

    private fun observeViewModel() {
        viewModel.chatsState.observe(this) { state ->
            when (state) {
                is MainViewModel.ChatsState.Loading -> {
                    if (isCreatingChat) {
                        binding.progressBar.visibility = View.VISIBLE
                        binding.createButton.isEnabled = false
                        binding.errorTextView.visibility = View.GONE
                    }
                }
                is MainViewModel.ChatsState.Success -> {
                    if (isCreatingChat) {
                        binding.progressBar.visibility = View.GONE
                        binding.createButton.isEnabled = true

                        Toast.makeText(this, "Чат успешно создан", Toast.LENGTH_SHORT).show()
                        finish()
                    }
                }
                is MainViewModel.ChatsState.Error -> {
                    if (isCreatingChat) {
                        binding.progressBar.visibility = View.GONE
                        binding.createButton.isEnabled = true
                        binding.errorTextView.text = state.message
                        binding.errorTextView.visibility = View.VISIBLE

                        Toast.makeText(this, state.message, Toast.LENGTH_LONG).show()
                        // Reset flag on error to allow retry
                        isCreatingChat = false
                    }
                }
            }
        }
    }
}
