package com.jiooption.trading.ui.auth

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.jiooption.trading.App
import com.jiooption.trading.MainActivity
import com.jiooption.trading.R
import com.jiooption.trading.network.ApiClient
import com.jiooption.trading.security.BiometricManager
import com.jiooption.trading.utils.*
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.*

/**
 * Login activity with email/password and biometric authentication
 */
class LoginActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "LoginActivity"
    }

    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var biometricManager: BiometricManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        setupViews()
        setupBiometric()
    }

    private fun setupViews() {
        val etEmail = findViewById<TextInputEditText>(R.id.etEmail)
        val etPassword = findViewById<TextInputEditText>(R.id.etPassword)
        val btnLogin = findViewById<MaterialButton>(R.id.btnLogin)
        val btnBiometric = findViewById<MaterialButton>(R.id.btnBiometric)
        val tvRegister = findViewById<TextView>(R.id.tvRegister)
        val progressBar = findViewById<ProgressBar>(R.id.progressBar)

        btnLogin.setOnClickListener {
            val email = etEmail.text.toString().trim()
            val password = etPassword.text.toString().trim()

            if (email.isEmpty()) {
                etEmail.error = "Email is required"
                return@setOnClickListener
            }
            if (!email.isValidEmail()) {
                etEmail.error = "Invalid email format"
                return@setOnClickListener
            }
            if (password.isEmpty()) {
                etPassword.error = "Password is required"
                return@setOnClickListener
            }

            performLogin(email, password, btnLogin, progressBar)
        }

        tvRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    private fun setupBiometric() {
        val btnBiometric = findViewById<MaterialButton>(R.id.btnBiometric)
        val storage = App.getSecureStorage()

        if (BiometricManager.isAvailable(this) && storage.getBoolean(Constants.PREF_BIOMETRIC_ENABLED)) {
            btnBiometric.visibility = View.VISIBLE
            biometricManager = BiometricManager(this)

            btnBiometric.setOnClickListener {
                biometricManager?.authenticate(
                    title = getString(R.string.biometric_title),
                    subtitle = getString(R.string.biometric_subtitle),
                    negativeButtonText = getString(R.string.biometric_negative),
                    onSuccess = {
                        // Already logged in with saved session, go to main
                        navigateToMain()
                    },
                    onError = { _, message ->
                        toast(message)
                    }
                )
            }

            // Auto-prompt biometric if saved session exists
            if (storage.isLoggedIn()) {
                btnBiometric.performClick()
            }
        } else {
            btnBiometric.visibility = View.GONE
        }
    }

    private fun performLogin(email: String, password: String, button: MaterialButton, progress: ProgressBar) {
        button.isEnabled = false
        progress.visibility = View.VISIBLE

        scope.launch {
            try {
                val response = withContext(Dispatchers.IO) {
                    ApiClient.getApiService().login(email, password)
                }

                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.success == true) {
                        // Save user session
                        val userData = body.data
                        App.getSecureStorage().saveUserCredentials(
                            userId = userData?.id?.toString() ?: "",
                            name = userData?.name ?: "",
                            email = userData?.email ?: email
                        )

                        toast("Login successful!")
                        navigateToMain()
                    } else {
                        toast(body?.error ?: body?.message ?: "Login failed")
                    }
                } else {
                    toast("Server error: ${response.code()}")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Login error", e)
                if (!NetworkUtils.isNetworkAvailable(this@LoginActivity)) {
                    toast(getString(R.string.no_internet))
                } else {
                    toast(getString(R.string.something_went_wrong))
                }
            } finally {
                button.isEnabled = true
                progress.visibility = View.GONE
            }
        }
    }

    private fun navigateToMain() {
        val intent = Intent(this, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
    }
}
