package com.useasy.callsdk.demo

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import com.useasy.callsdk.CallSDK
import com.useasy.callsdk.config.Environment
import com.useasy.callsdk.config.LogConfig
import com.useasy.callsdk.config.SDKConfig
import com.useasy.callsdk.listener.InitListener

/**
 * 登录页面
 */
class LoginActivity : BaseActivity(), View.OnClickListener {

    private lateinit var etAccount: EditText
    private lateinit var etPassword: EditText
    private lateinit var ivClearAccount: ImageView
    private lateinit var ivClearPass: ImageView
    private lateinit var reLogin: ConstraintLayout
    private lateinit var tvLoging: TextView
    private lateinit var pvLoging: ProgressBar

    private var accountHasText = false
    private var passHasText = false

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

        initViews()
        setupViews()
        initAccountContentListener()
    }

    private fun initViews() {
        etAccount = findViewById(R.id.et_account)
        etPassword = findViewById(R.id.et_password)
        ivClearAccount = findViewById(R.id.iv_clear_account)
        ivClearPass = findViewById(R.id.iv_clear_pass)
        reLogin = findViewById(R.id.re_login)
        tvLoging = findViewById(R.id.tv_loging)
        pvLoging = findViewById(R.id.pv_loging)
    }

    private fun setupViews() {
        ivClearAccount.setOnClickListener(this)
        ivClearPass.setOnClickListener(this)
        reLogin.setOnClickListener(this)

    }

    private fun initAccountContentListener() {
        etAccount.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (TextUtils.isEmpty(s)) {
                    ivClearAccount.visibility = View.GONE
                    reLogin.isSelected = false
                    reLogin.isClickable = false
                    accountHasText = false
                } else {
                    ivClearAccount.visibility = View.VISIBLE
                    accountHasText = true
                    if (passHasText) {
                        reLogin.isSelected = true
                        reLogin.isClickable = true
                    }
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })

        etPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (TextUtils.isEmpty(s)) {
                    ivClearPass.visibility = View.GONE
                    passHasText = false
                    reLogin.isSelected = false
                    reLogin.isClickable = false
                } else {
                    ivClearPass.visibility = View.VISIBLE
                    passHasText = true
                    if (accountHasText) {
                        reLogin.isSelected = true
                        reLogin.isClickable = true
                    }
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_clear_account -> {
                etAccount.setText("")
            }

            R.id.iv_clear_pass -> {
                etPassword.setText("")
            }

            R.id.re_login -> {
                dealLogin()
            }
        }
    }

    private fun dealLogin() {
        val account = etAccount.text.toString().trim()
        val password = etPassword.text.toString().trim()

        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show()
            return
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show()
            return
        }

        setLeadingView()

        val config = SDKConfig(
            username = account, password = password, baseUrl = Environment.PRODUCTION,
            logConfig = LogConfig(
                enableLog = true,
                logLevel = Log.DEBUG,
                logFilePath = null,
                fileLoggingEnabled = true,
                consoleLogEnabled = true,
            )
        )

        // 设置被踢下线监听（独立于 init，全局生效）
        CallSDK.setOnKickedListener {
            handleKicked()
        }

        // 初始化并登录
        CallSDK.init(
            application,
            config,
            object : InitListener {
                override fun onInitSuccess() {
                    setNoLeadingView()
                    startDialActivity()
                    finish()
                }

                override fun onInitFailed(errorCode: Int, errorMsg: String?) {
                    setNoLeadingView()
                    Toast.makeText(this@LoginActivity, errorMsg, Toast.LENGTH_SHORT).show()
                }
            }
        )
    }

    private fun startDialActivity() {
        val intent = Intent(this, DialActivity::class.java)
        startActivity(intent)
    }

    private fun handleKicked() {
        // 如果已经在登录页，只需要重置状态
        if (!isFinishing && !isDestroyed) {
            setNoLeadingView()
            Toast.makeText(this, "账号被踢下线，请重新登录", Toast.LENGTH_SHORT).show()
            CallSDK.logout()
        }
    }


    private fun setLeadingView() {
        reLogin.isClickable = false
        pvLoging.visibility = View.VISIBLE
        tvLoging.text = "登录中..."
    }

    private fun setNoLeadingView() {
        reLogin.isClickable = true
        pvLoging.visibility = View.GONE
        tvLoging.text = "登录"
    }
}

