package com.seatel.mobilehall.ui.home.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.seatel.mobilehall.R
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import androidx.core.net.toUri
import com.seatel.mobilehall.databinding.ActivityAcledaBinding

class AcledaActivity : BaseActivity<ActivityAcledaBinding>() {

    private lateinit var mUrlPay: String
    private var mAmount: Double = 0.0
    private var mPhoneNumber: String? = null
    private var isAbleBack: Boolean = false
    private var isShowValentineDayPromotion = false


    private val mWebViewClient = object : WebViewClient() {

//        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
//            println("===>>> WebView onPageStarted: $url")
//            super.onPageStarted(view, url, favicon)
//        }


        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            showHideLoading(false)

        }

        override fun onReceivedError(
            view: WebView, request: WebResourceRequest, error: WebResourceError
        ) {
            super.onReceivedError(view, request, error)
            //closeWingPaymentWithError()
            closeAcledaPaymentWithError()
        }


        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            val url = request?.url.toString()
            val uri = request?.url.toString()
            val host = request?.url?.host ?: ""
            Log.d("TAG::>>>", "shouldOverrideUrlLoading: url=$url host=$host")
            println("===> URI: $uri")
            // SUCCESS
            if (url.contains("_paymentresult=SUCCESS")) {
                TopUpSuccessActivity.lunch(
                    this@AcledaActivity,
                    Constant.TOPUP_SUCCESS,
                    mAmount.toString(),
                    mPhoneNumber ?: ""
                )
                finish()
                return true
            }

            // CANCEL / SESSION EXPIRED
            if (url.contains("cancel")) {
                val uri = url.toUri()
                val resultMsg = uri.getQueryParameter("_resultmsg") ?: "Payment failed"
                exitAcledaPayment(false)
                return true
            }

            val allowedHosts = listOf(
                "yes.com.kh",
                "dev.yes.com.kh",
                "api.yes.com.kh",
                "acleda.com.kh",
                "api-dev.yes.com.kh"
            )
            println("===> allowedHosts: $allowedHosts")
            if (allowedHosts.any { host.contains(it) }) return false
            println("===> host return : $host")
            startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
            return true
        }


    }

    private fun closeAcledaPaymentWithError() {

        showHideLoading(false)/* SeatelAlertDialog.with(this, getString(R.string.message_wing_error)).setCancelable(true)
             .setPositiveButton(getString(R.string.yes)) { _, _ ->
                 exitWingPayment(false)
             }.show()*/
    }

    private fun closePaymentProcress() {

        if (binding.webViewAcleda.canGoBack()) {
            binding.webViewAcleda.goBack()
        } else {
            showHideLoading(false)
            SeatelAlertDialog.with(this, getString(R.string.cancel_process_payment))
                .setCancelable(true).setPositiveButton(getString(R.string.yes)) { _, _ ->
                    exitAcledaPayment(false)
                }.setNegativeButton(getString(R.string.cancel)) { dailog, _ ->
                    dailog.dismiss()
                }.show()
        }
    }


    override fun isDisplayBackgroundBlur(): Boolean {
        return false
    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }

    override fun isStatusBarColorDark(): Boolean {
        return true
    }


    override fun getViewBinding(): ActivityAcledaBinding {
        return ActivityAcledaBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        println("===> OnCreateAcledaCalled")
        activityEnterFadeInAnimation()
        showHideLoading(true)
        init()
    }

    private fun showHideLoading(isShow: Boolean) {
        if (isShow) {
            binding.errorView.visibility = View.VISIBLE
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        } else {
            binding.errorView.visibility = View.GONE
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun init() {
        mUrlPay = intent.getStringExtra("payment_url") ?: ""
        println("===> Payment URL: $mUrlPay")
       // Log.d("TAG::>>>", "acledaUrl: $mUrlPay")

//        if (mUrlPay.isEmpty()) {
//            closeAcledaPaymentWithError()
//            return
//        }

        isShowValentineDayPromotion = intent.getBooleanExtra("show_valentine_promotion", false)
        isAbleBack = intent.getBooleanExtra("is_able_back", false)
        mAmount = intent.getDoubleExtra("top_amount", 0.0)
        mPhoneNumber = intent.getStringExtra(Constant.PHONE_NUMBER)

        binding.webViewAcleda.settings.javaScriptEnabled = true
        binding.webViewAcleda.webViewClient = mWebViewClient

        binding.webViewAcleda.loadUrl(mUrlPay)
    }



    private fun exitAcledaPayment(isSuccess: Boolean) {
        showHideLoading(false)

        if (isSuccess) {
            val intent = Intent(this, PaymentActivity::class.java)
            intent.putExtra("show_valentine_promotion", isShowValentineDayPromotion)
            setResult(Activity.RESULT_OK, intent)
        }
        activityExitLeftAnimation()
        finish()

    }

    override fun onBackPressed() {
        super.onBackPressed()
        closePaymentProcress()
    }



    override fun onPause() {
        super.onPause()
        binding.webViewAcleda.onPause()
    }

    override fun onResume() {
        super.onResume()
        binding.webViewAcleda.onResume()
    }

    companion object {
        fun lunch(
            context: Context,
            url: String,
            amount: Double,
            isAbleBackPress: Boolean = false,
            showValentineDayPromotion: Boolean = false,
            phoneNumber: String,
        ) {
            val i = Intent(context, AcledaActivity::class.java)
            i.putExtra("payment_url", url)
            i.putExtra("top_amount", amount)
            i.putExtra("is_able_back", isAbleBackPress)
           // i.putExtra("show_valentine_promotion", showValentineDayPromotion)
            i.putExtra(Constant.PHONE_NUMBER, phoneNumber)
            (context as Activity).startActivityForResult(i, Constant.REQUEST_ACLEDA)
        }
    }


}