package com.crm.chat.ui.profile

import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.crm.chat.databinding.ActivityProfileBinding
import com.bumptech.glide.Glide
import com.crm.chat.data.api.ApiClient
import com.crm.chat.data.model.UpdateUserRequest
import com.crm.chat.data.model.User
import com.crm.chat.data.repository.UserRepository
import kotlinx.coroutines.launch

class ProfileActivity : AppCompatActivity() {

    private lateinit var binding: ActivityProfileBinding
    private lateinit var prefs: SharedPreferences
    private lateinit var apiClient: ApiClient
    private lateinit var userRepository: UserRepository

    private var currentUser: User? = null
    private var selectedAvatarUri: Uri? = null

    private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { handleImageSelection(it) }
    }

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

        prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)

        // Initialize API client and repository
        val baseUrl = prefs.getString("server_url", "") ?: ""
        val apiKey = prefs.getString("api_key", "") ?: ""
        val token = prefs.getString("auth_token", "") ?: ""
        apiClient = ApiClient(baseUrl, apiKey, token)
        userRepository = UserRepository(apiClient)

        setupToolbar()
        loadCurrentUserData()
        setupListeners()
    }

    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "Профиль"
    }

    private fun loadCurrentUserData() {
        binding.progressBar.visibility = android.view.View.VISIBLE

        val userId = prefs.getLong("current_user_id", 0L)
        if (userId > 0) {
            lifecycleScope.launch {
                try {
                    val result = userRepository.getUserById(userId)
                    if (result.isSuccess) {
                        currentUser = result.getOrNull()
                        populateUI()
                    } else {
                        // Fallback to preferences data
                        loadFromPreferences()
                    }
                } catch (e: Exception) {
                    // Fallback to preferences data
                    loadFromPreferences()
                } finally {
                    binding.progressBar.visibility = android.view.View.GONE
                }
            }
        } else {
            loadFromPreferences()
        }
    }

    private fun loadFromPreferences() {
        val userId = prefs.getLong("current_user_id", 0L)
        val userName = prefs.getString("user_name", "")
        val userEmail = prefs.getString("user_email", "")
        val userPhone = prefs.getString("user_phone", "")
        val userAvatarUrl = prefs.getString("user_avatar_url", "")

        // Parse full name into first and last name
        val nameParts = userName?.split(" ", limit = 2) ?: emptyList()
        val firstName = nameParts.getOrNull(0) ?: ""
        val lastName = nameParts.getOrNull(1)

        // Create user object from preferences
        currentUser = User(
            id = userId,
            firstName = firstName,
            lastName = lastName,
            email = userEmail ?: "",
            phone = userPhone,
            avatarUrl = userAvatarUrl,
            position = prefs.getString("user_position", null)
        )

        populateUI()
        binding.progressBar.visibility = android.view.View.GONE
    }

    private fun populateUI() {
        currentUser?.let { user ->
            binding.firstNameEditText.setText(user.firstName)
            binding.lastNameEditText.setText(user.lastName)
            binding.emailEditText.setText(user.email)
            binding.phoneEditText.setText(user.phone)

            if (!user.avatarUrl.isNullOrEmpty()) {
                Glide.with(this)
                    .load(user.avatarUrl)
                    .circleCrop()
                    .placeholder(com.crm.chat.R.mipmap.ic_launcher)
                    .into(binding.avatarImageView)
            } else {
                binding.avatarImageView.setImageResource(com.crm.chat.R.mipmap.ic_launcher)
            }
        }
    }

    private fun setupListeners() {
        binding.avatarImageView.setOnClickListener {
            openImagePicker()
        }

        binding.saveButton.setOnClickListener {
            saveProfile()
        }
    }

    private fun openImagePicker() {
        pickImageLauncher.launch("image/*")
    }

    private fun handleImageSelection(uri: Uri) {
        selectedAvatarUri = uri

        // Display selected image
        Glide.with(this)
            .load(uri)
            .circleCrop()
            .into(binding.avatarImageView)

        Toast.makeText(this, "Изображение выбрано", Toast.LENGTH_SHORT).show()
    }

    private fun saveProfile() {
        val firstName = binding.firstNameEditText.text.toString().trim()
        val lastName = binding.lastNameEditText.text.toString().trim()
        val email = binding.emailEditText.text.toString().trim()
        val phone = binding.phoneEditText.text.toString().trim()

        if (firstName.isEmpty()) {
            binding.errorTextView.text = "Введите имя"
            binding.errorTextView.visibility = android.view.View.VISIBLE
            return
        }

        if (email.isEmpty()) {
            binding.errorTextView.text = "Введите email"
            binding.errorTextView.visibility = android.view.View.VISIBLE
            return
        }

        binding.progressBar.visibility = android.view.View.VISIBLE
        binding.saveButton.isEnabled = false

        lifecycleScope.launch {
            try {
                currentUser?.let { user ->
                    // First upload avatar if selected
                    if (selectedAvatarUri != null) {
                        val avatarResult = userRepository.uploadUserAvatar(user.id, selectedAvatarUri!!, contentResolver)
                        if (avatarResult.isSuccess) {
                            // Update current user with new avatar URL
                            currentUser = avatarResult.getOrNull()
                        }
                    }

                    // Update user profile
                    val updateRequest = UpdateUserRequest(
                        firstName = firstName,
                        lastName = lastName,
                        email = email,
                        phone = phone,
                        position = user.position
                    )

                    val result = userRepository.updateUser(user.id, updateRequest)
                    if (result.isSuccess) {
                        // Save to preferences
                        val fullName = "${firstName} ${lastName}".trim()
                        prefs.edit()
                            .putString("user_name", fullName)
                            .putString("user_email", email)
                            .putString("user_phone", phone)
                            .apply()

                        binding.errorTextView.visibility = android.view.View.GONE
                        Toast.makeText(this@ProfileActivity, "Профиль сохранен", Toast.LENGTH_SHORT).show()
                        finish()
                    } else {
                        binding.errorTextView.text = "Ошибка сохранения профиля"
                        binding.errorTextView.visibility = android.view.View.VISIBLE
                    }
                }
            } catch (e: Exception) {
                binding.errorTextView.text = "Ошибка: ${e.localizedMessage}"
                binding.errorTextView.visibility = android.view.View.VISIBLE
            } finally {
                binding.progressBar.visibility = android.view.View.GONE
                binding.saveButton.isEnabled = true
            }
        }
    }

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