package com.crm.chat.ui.profile

import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
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 var isReadOnlyProfile: Boolean = false

    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)

        // Check if we're viewing another user's profile
        val targetUserId = intent.getLongExtra("user_id", -1L)
        val currentUserId = prefs.getLong("current_user_id", 0L)
        
        // If targetUserId is provided and different from current user, show read-only profile
        isReadOnlyProfile = targetUserId != -1L && targetUserId != currentUserId

        // 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 targetUserId = intent.getLongExtra("user_id", -1L)
        val currentUserId = prefs.getLong("current_user_id", 0L)

        // If viewing another user's profile, load their data
        if (isReadOnlyProfile && targetUserId != -1L) {
            lifecycleScope.launch {
                try {
                    val result = userRepository.getUserById(targetUserId)
                    if (result.isSuccess) {
                        currentUser = result.getOrNull()
                        populateUI()
                    } else {
                        // Fallback to showing basic info
                        currentUser = User(
                            id = targetUserId,
                            firstName = "User",
                            lastName = targetUserId.toString(),
                            email = "user@company.com",
                            phone = null,
                            avatarUrl = null,
                            position = null
                        )
                        populateUI()
                    }
                } catch (e: Exception) {
                    // Fallback to showing basic info
                    currentUser = User(
                        id = targetUserId,
                        firstName = "User",
                        lastName = targetUserId.toString(),
                        email = "user@company.com",
                        phone = null,
                        avatarUrl = null,
                        position = null
                    )
                    populateUI()
                } finally {
                    binding.progressBar.visibility = android.view.View.GONE
                }
            }
        } else {
            // Loading current user's profile
            if (currentUserId > 0) {
                lifecycleScope.launch {
                    try {
                        val result = userRepository.getUserById(currentUserId)
                        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(getUserColor(user.id))
                    .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>?) {
                            binding.avatarImageView.setImageDrawable(resource)
                        }

                        override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {
                            showInitialsAvatar(user)
                        }
                    })
                    .into(binding.avatarImageView)
            } else {
                showInitialsAvatar(user)
            }
        }
    }

    private fun setupListeners() {
        if (isReadOnlyProfile) {
            // Read-only profile - disable editing
            binding.firstNameEditText.isEnabled = false
            binding.lastNameEditText.isEnabled = false
            binding.emailEditText.isEnabled = false
            binding.phoneEditText.isEnabled = false
            binding.saveButton.visibility = android.view.View.GONE
            binding.avatarImageView.isClickable = false
            binding.avatarImageView.alpha = 0.5f
        } else {
            // Editable profile
            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
            }
        }
    }

    private fun showInitialsAvatar(user: User) {
        // Generate initials from user name
        val initials = "${user.firstName.take(1)}${user.lastName?.take(1) ?: ""}".uppercase()

        // Background color for the avatar
        val backgroundColor = getUserColor(user.id)

        // Create circular bitmap with initials
        val size = 384
        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.4f // 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)

        // Set the bitmap to the ImageView
        binding.avatarImageView.setImageBitmap(bitmap)
    }

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

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