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.utils.*
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.*

/**
 * Registration activity
 */
class RegisterActivity : AppCompatActivity() {

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

    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        setupViews()
    }

    private fun setupViews() {
        val etName = findViewById<TextInputEditText>(R.id.etName)
        val etEmail = findViewById<TextInputEditText>(R.id.etEmail)
        val etPhone = findViewById<TextInputEditText>(R.id.etPhone)
        val etPassword = findViewById<TextInputEditText>(R.id.etPassword)
        val etConfirmPassword = findViewById<TextInputEditText>(R.id.etConfirmPassword)
        val btnRegister = findViewById<MaterialButton>(R.id.btnRegister)
        val tvLogin = findViewById<TextView>(R.id.tvLogin)
        val progressBar = findViewById<ProgressBar>(R.id.progressBar)

        btnRegister.setOnClickListener {
            val name = etName.text.toString().trim()
            val email = etEmail.text.toString().trim()
            val phone = etPhone.text.toString().trim()
            val password = etPassword.text.toString()
            val confirmPassword = etConfirmPassword.text.toString()

            // Validation
            if (name.isEmpty()) { etName.error = "Name is required"; return@setOnClickListener }
            if (name.length < 2) { etName.error = "Name too short"; return@setOnClickListener }
            if (email.isEmpty()) { etEmail.error = "Email is required"; return@setOnClickListener }
            if (!email.isValidEmail()) { etEmail.error = "Invalid email"; return@setOnClickListener }
            if (phone.isEmpty()) { etPhone.error = "Phone is required"; return@setOnClickListener }
            if (!phone.isValidPhone()) { etPhone.error = "Invalid phone (10 digits)"; return@setOnClickListener }
            if (password.isEmpty()) { etPassword.error = "Password is required"; return@setOnClickListener }
            if (!password.isStrongPassword()) { etPassword.error = "Min 8 chars, 1 upper, 1 lower, 1 number"; return@setOnClickListener }
            if (password != confirmPassword) { etConfirmPassword.error = "Passwords don't match"; return@setOnClickListener }

            performRegister(name, email, phone, password, confirmPassword, btnRegister, progressBar)
        }

        tvLogin.setOnClickListener { finish() }
    }

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

        scope.launch {
            try {
                val response = withContext(Dispatchers.IO) {
                    ApiClient.getApiService().register(name, email, phone, password, confirmPassword)
                }

                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.success == true) {
                        val userData = body.data
                        App.getSecureStorage().saveUserCredentials(
                            userId = userData?.id?.toString() ?: "",
                            name = userData?.name ?: name,
                            email = userData?.email ?: email
                        )
                        toast("Registration successful!")
                        val intent = Intent(this@RegisterActivity, MainActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                        finish()
                    } else {
                        toast(body?.error ?: body?.message ?: "Registration failed")
                    }
                } else {
                    toast("Server error: ${response.code()}")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Register error", e)
                if (!NetworkUtils.isNetworkAvailable(this@RegisterActivity)) {
                    toast(getString(R.string.no_internet))
                } else {
                    toast(getString(R.string.something_went_wrong))
                }
            } finally {
                button.isEnabled = true
                progress.visibility = View.GONE
            }
        }
    }

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