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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
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.databinding.ActivityAliPayMpayPaymentBinding
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 java.util.Locale

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
open class AliPayPaymentActivity : BaseActivity<ActivityAliPayMpayPaymentBinding>() {

    private lateinit var mUrlPay: String
    private var mAmount: Double = 0.0
    private var isABAPay = false
    private var isShowValentineDayPromotion = false
    private var isOpenDeepLink = false

    fun getWebClient(): WebViewClient {
        return mWebViewClient
    }

    private val mWebViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            if (url != null && view != null) {
                Log.d("---PageStarted", "onPageStarted: $url")
                onPageFinish(view, url)
            }
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            hideProgress()
        }

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

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            val url = request?.url.toString()
            val host = request?.url?.host.toString()
            val scheme = request?.url?.scheme.toString()
            Log.d("TAG::>>>", "shouldOverrideUrlLoading: $url $host $scheme")
            if (isPaywayDeeplink(host, scheme)) {
                openDeeplink(url)
                return false
            }
            return isOverrideUrlLoading(view, request)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            val uri = Uri.parse(url)
            val host = uri.host
            val scheme = uri.scheme
            Log.d("TAG::>>>", "shouldOverrideUrlLoading: $uri $host $scheme")
            if (isPaywayDeeplink(host!!, scheme!!)) {
                if (url != null) {
                    openDeeplink(url)
                }
                return false
            }
            return isOverrideUrlLoading(view, url)
        }
    }

    open fun isOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
        return false
    }

    open fun isOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        return false
    }


    private fun openDeeplink(url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        val packageManager = this.packageManager
        val resolvedActivities = packageManager.queryIntentActivities(intent, 0)
        if (resolvedActivities.size > 0)
            startActivity(intent)
        else gotoPlayStore()
        isOpenDeepLink = true
    }

    private fun gotoPlayStore() {
        try {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=com.paygo24.ibank")
                )
            )
        } catch (obj: android.content.ActivityNotFoundException) {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=com.paygo24.ibank")
                )
            )
        }

    }

    private fun isPaywayDeeplink(host: String, scheme: String): Boolean {
        return host.equals(Constant.ABA_HOST, true) && scheme.equals(Constant.ABA_SCHEME, true)
    }

    private fun closeWingPaymentWithError() {

        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.webViewWing.canGoBack()) {
            binding.webViewWing.goBack()
        } else {
            showHideLoading(false)
            SeatelAlertDialog.with(this, getString(R.string.cancel_process_payment))
                .setCancelable(true).setPositiveButton(getString(R.string.yes)) { _, _ ->
                    exitWingPayment(false)
                }.setNegativeButton(getString(R.string.cancel)) { dailog, _ ->
                    dailog.dismiss()
                }.show()
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //  setContentView(R.layout.activity_ali_pay_mpay_payment)
        activityEnterRightAnimation()

        baseBinding.textViewTitleBar.text = intent.getStringExtra("title_payment")!!
            .replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
        activityEnterFadeInAnimation()
        //     showHideLoading(true)
        showProgress()
        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
        }
    }

    override fun getToolbarTitle(): String {
        return ""
    }

    private fun init() {

        isShowValentineDayPromotion = intent.getBooleanExtra("show_valentine_promotion", false)
        isABAPay = intent.getBooleanExtra("is_aba_pay", false)
        mAmount = intent.getDoubleExtra("top_amount", 0.0)
        binding.webViewWing.isVerticalScrollBarEnabled = true
        binding.webViewWing.settings.javaScriptEnabled = true
        binding.webViewWing.webViewClient = mWebViewClient
        mUrlPay = intent.getStringExtra("payment_url").toString()
        binding.webViewWing.loadUrl(mUrlPay)
        Log.d("---alipayment", "init: $mUrlPay")
    }


    private fun onPageFinish(webView: WebView, url: String) {

        when {
            url.contains("result=success") -> {
                exitWingPayment(true)
            }

            url.contains("result=error") -> {
                exitWingPayment(false)
            }
        }
    }

    private fun exitWingPayment(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 onResume() {
        super.onResume()
        binding.webViewWing.onResume()
        isOpenDeepLink = false
    }

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

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

    companion object {
        fun lunch(
            context: Context,
            url: String,
            amount: Double,
            title: String,
            ShowValentineDayPromotion: Boolean = false,
            isABA: Boolean = false
        ) {
            val i = Intent(context, AliPayPaymentActivity::class.java)
            i.putExtra("payment_url", url)
            i.putExtra("top_amount", amount)
            i.putExtra("title_payment", title)
            i.putExtra("is_aba_pay", isABA)
            i.putExtra("show_valentine_promotion", ShowValentineDayPromotion)
            (context as Activity).startActivityForResult(i, Constant.REQUEST_WING)
        }
    }
}
