package com.crm.chat.ui.auth

import android.content.Intent
import android.content.SharedPreferences
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.databinding.ActivityAuthBinding
import com.crm.chat.ui.main.MainActivity

class AuthActivity : AppCompatActivity() {

    private lateinit var binding: ActivityAuthBinding
    private val viewModel: AuthViewModel by viewModels()

    private var lastEmail: String? = null
    private var lastPassword: String? = null
    private var isAutoLoginAttempt = false

    companion object {
        private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialize notification channel
        com.crm.chat.utils.NotificationHelper.createNotificationChannel(this)

        // Request notification permission on Android 13+
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            if (androidx.core.content.ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.POST_NOTIFICATIONS
                ) != android.content.pm.PackageManager.PERMISSION_GRANTED
            ) {
                androidx.core.app.ActivityCompat.requestPermissions(
                    this,
                    arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
                    NOTIFICATION_PERMISSION_REQUEST_CODE
                )
            }
        }

        binding = ActivityAuthBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setupViews()

        // Initialize default settings on first launch
        val prefs: SharedPreferences = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        initializeDefaultSettings(prefs)

        // Try automatic login on app startup (including after phone restart)
        val token = prefs.getString("auth_token", null)
        val serverUrl = prefs.getString("server_url", null)
        val apiKey = prefs.getString("api_key", null)
        val savedEmail = prefs.getString("saved_email", null)
        val savedPassword = prefs.getString("saved_password", null)

        if (token != null && serverUrl != null && apiKey != null && savedEmail != null && savedPassword != null) {
            // Try automatic login with saved credentials
            attemptAutoLogin(savedEmail, savedPassword, serverUrl, apiKey)
        } else {
            // Show login form if no saved credentials or incomplete data
            showLoginForm()
        }
    }

    private fun attemptAutoLogin(email: String, password: String, serverUrl: String, apiKey: String) {
        isAutoLoginAttempt = true
        lastEmail = email
        lastPassword = password

        // Show loading state for auto-login
        binding.progressBar.visibility = View.VISIBLE
        binding.titleTextView.text = "Автоматический вход..."
        binding.descriptionTextView.visibility = View.GONE
        binding.emailInputLayout.visibility = View.GONE
        binding.passwordInputLayout.visibility = View.GONE
        binding.loginButton.visibility = View.GONE

        // Attempt login with custom server
        viewModel.loginWithCustomServer(serverUrl, apiKey, email, password)
    }

    private fun showLoginForm() {
        isAutoLoginAttempt = false
        binding.progressBar.visibility = View.GONE
        binding.titleTextView.text = getString(R.string.login_title)
        binding.descriptionTextView.visibility = View.VISIBLE
        binding.emailInputLayout.visibility = View.VISIBLE
        binding.passwordInputLayout.visibility = View.VISIBLE
        binding.loginButton.visibility = View.VISIBLE
        binding.loginButton.isEnabled = true
        binding.loginButton.text = "Войти"
    }

    private fun setupViews() {
        observeViewModel()

        binding.loginButton.setOnClickListener {
            val email = binding.emailEditText.text.toString().trim()
            val password = binding.passwordEditText.text.toString().trim()

            if (email.isBlank()) {
                binding.errorTextView.text = "Введите email"
                binding.errorTextView.visibility = View.VISIBLE
                return@setOnClickListener
            }

            if (password.isBlank()) {
                binding.errorTextView.text = "Введите пароль"
                binding.errorTextView.visibility = View.VISIBLE
                return@setOnClickListener
            }

            isAutoLoginAttempt = false
            lastEmail = email
            lastPassword = password

            viewModel.login(email, password)
        }

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

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

        binding.additionalSettingsButton.setOnClickListener {
            openAdditionalSettings()
        }
    }

    private fun observeViewModel() {
        viewModel.loginState.observe(this) { state ->
            when (state) {
                is AuthViewModel.LoginState.Loading -> {
                    binding.progressBar.visibility = View.VISIBLE
                    binding.loginButton.isEnabled = false
                    binding.errorTextView.visibility = View.GONE
                    binding.loginButton.text = "Подключение..."
                }
                is AuthViewModel.LoginState.Success -> {
                    isAutoLoginAttempt = false
                    binding.progressBar.visibility = View.GONE
                    binding.loginButton.isEnabled = true
                    binding.loginButton.text = "Войти"

                    val token = state.authResponse.token
                    if (!token.isNullOrBlank()) {
                        // Save auth data including credentials for auto-login
                        saveAuthData(token, state.serverUrl, state.authResponse.userId, lastEmail ?: "", lastPassword ?: "")

                        // Navigate to main activity
                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    } else {
                        binding.errorTextView.text = "Ошибка: сервер вернул пустой токен. Проверьте правильность email и пароля."
                        binding.errorTextView.visibility = View.VISIBLE
                    }
                }
                is AuthViewModel.LoginState.Error -> {
                    binding.progressBar.visibility = View.GONE
                    binding.loginButton.isEnabled = true
                    binding.loginButton.text = "Войти"

                    if (isAutoLoginAttempt) {
                        // Auto-login failed, show login form with error
                        isAutoLoginAttempt = false
                        showLoginForm()
                        binding.errorTextView.text = "Автоматический вход не удался. Введите данные вручную."
                        binding.errorTextView.visibility = View.VISIBLE
                    } else {
                        binding.errorTextView.text = state.message
                        binding.errorTextView.visibility = View.VISIBLE
                        Toast.makeText(this, state.message, Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }

    private fun openAdditionalSettings() {
        val intent = Intent(this, com.crm.chat.ui.settings.SettingsActivity::class.java)
        startActivity(intent)
    }

    private fun saveAuthData(token: String, serverUrl: String, userId: Long, email: String, password: String) {
        val prefs: SharedPreferences = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)
        prefs.edit()
            .putString("auth_token", token)
            .putString("server_url", serverUrl)
            .putString("api_key", com.crm.chat.data.AppConstants.API_KEY)
            .putLong("current_user_id", userId)
            .putString("saved_email", email)
            .putString("saved_password", password)
            .apply()
    }

    private fun initializeDefaultSettings(prefs: SharedPreferences) {
        // Check if this is first launch by checking if server_url is set
        val serverUrl = prefs.getString("server_url", null)
        val apiKey = prefs.getString("api_key", null)

        if (serverUrl.isNullOrEmpty() || apiKey.isNullOrEmpty()) {
            // First launch - set default settings
            prefs.edit()
                .putString("server_url", com.crm.chat.data.AppConstants.SERVER_URL)
                .putString("api_key", com.crm.chat.data.AppConstants.API_KEY)
                .apply()
        }
    }
}
