package com.nivesh.production.niveshfd.fd.ui.activity

import android.app.Dialog
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.nivesh.production.niveshfd.R
import com.nivesh.production.niveshfd.databinding.FragmentNiveshfdStepFiveBinding
import com.nivesh.production.niveshfd.fd.api.ApiClient
import com.nivesh.production.niveshfd.fd.db.PreferenceManager
import com.nivesh.production.niveshfd.fd.model.PaymentReQueryRequest
import com.nivesh.production.niveshfd.fd.model.PaymentReQueryResponse
import com.nivesh.production.niveshfd.fd.repositories.MainRepository
import com.nivesh.production.niveshfd.fd.ui.providerfactory.FDModelProviderFactory
import com.nivesh.production.niveshfd.fd.util.Common
import com.nivesh.production.niveshfd.fd.util.Constants
import com.nivesh.production.niveshfd.fd.util.ProgressUtil
import com.nivesh.production.niveshfd.fd.util.Resource
import com.nivesh.production.niveshfd.fd.viewModel.BajajFDViewModel

class PaymentActivity : BaseActivity() {

    private lateinit var binding: FragmentNiveshfdStepFiveBinding
    var dialogWebView: Dialog? = null
    lateinit var viewModel: BajajFDViewModel
    private var clientCode : String = ""
    var uniqueId : String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(
            this@PaymentActivity,
            FDModelProviderFactory(MainRepository(ApiClient.getApiClient))
        )[BajajFDViewModel::class.java]
        binding = FragmentNiveshfdStepFiveBinding.inflate(layoutInflater)

        binding.btnViewOrder.setOnClickListener {
            (this@PaymentActivity).setResult(RESULT_OK)
            (this@PaymentActivity).finish()
        }

        binding.tvRetry.setOnClickListener {
            (this@PaymentActivity).setResult(RESULT_OK)
            (this@PaymentActivity).finish()
        }
        if (intent != null){

            clientCode = intent.getStringExtra("clientCode").toString()
            paymentDialog(intent.getStringExtra("url").toString(), intent.getStringExtra("value").toString())
        }

    }

    private fun paymentDialog(payUrl: String, value: String) {
        Log.e("payUrl", "-->$payUrl")
        Log.e("value", "-->$value")
        dialogWebView = Dialog(this@PaymentActivity)
        dialogWebView!!.setContentView(R.layout.row_fd_pay1)
        dialogWebView!!.setCancelable(true)
        val tvCancel = dialogWebView!!.findViewById<TextView>(R.id.tvCancel)
        tvCancel.setOnClickListener {
            dialogWebView!!.dismiss()
            (this@PaymentActivity).setResult(RESULT_OK)
            (this@PaymentActivity).finish()
        }
        val lp = WindowManager.LayoutParams()
        lp.copyFrom(dialogWebView!!.window?.attributes)
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        dialogWebView!!.window?.attributes = lp
        val wVPay = dialogWebView!!.findViewById<WebView>(R.id.wVPay)
        wVPay.settings.javaScriptEnabled = true
        wVPay.settings.domStorageEnabled = true
        wVPay.loadData(
            "<form name=\"frm\" action=\"$payUrl\" method=\"post\"> \n" + " <input type=\"hidden\" name=\"msg\" value=\"$value\"> \n" + " </form> \n" +
                    "<script type=\"text/javascript\"> \n" + "document.forms[\"frm\"].submit(); \n" + "</script>",
            "text/html",
            "UTF-8"
        )
        wVPay.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.e("onPageStarted", "-->$url")
                if (url.isNotEmpty() && url.contains(Constants.paymentUrl)) {
                    if (dialogWebView!!.isShowing) {
                        dialogWebView!!.dismiss()
                        paymentReQueryApi()
                    }
                }
            }
        }
        dialogWebView!!.show()
    }

    fun paymentReQueryApi() {
        if (Common.isNetworkAvailable(this)) {
            val paymentReQueryRequest = PaymentReQueryRequest()
            paymentReQueryRequest.UniqueId = uniqueId
            paymentReQueryRequest.NiveshClientCode = clientCode
            ProgressUtil.showLoading(this@PaymentActivity)
            viewModel.getPaymentReQuery(
                paymentReQueryRequest,
                PreferenceManager(this@PaymentActivity).getToken(),
                this
            )
            viewModel.getPaymentReQueryMutableData.observe(this) { response ->
                when (response) {
                    is Resource.Success -> {
                        Log.e("paymentReQueryApi ", "response -->$response")
                        val paymentReQueryResponse: PaymentReQueryResponse =
                            Gson().fromJson(
                                response.data?.toString(),
                                PaymentReQueryResponse::class.java
                            )
                        paymentReQueryResponse.Response.StatusCode.let { code ->
                            when (code) {
                                650 -> ""
                                else -> {
                                    getData(paymentReQueryResponse)
                                }
                            }
                        }
                    }
                    is Resource.Error -> {
                        response.message?.let { message ->
                            Common.showDialogValidation(this@PaymentActivity, message)
                        }
                    }
                    is Resource.Loading -> {
                        ProgressUtil.hideLoading()
                    }
                    is Resource.DataError -> {

                    }
                    else -> {
                        Common.showDialogValidation(this@PaymentActivity, response.message)
                    }
                }
            }
        }
    }


    private fun getData(paymentReQueryResponse: PaymentReQueryResponse) {
        if (paymentReQueryResponse.Response.StatusCode == 200) {
            if (paymentReQueryResponse.Response.Message.isNotEmpty()) {
                val arrOfStr: List<String> =
                    paymentReQueryResponse.Response.Message.split(" ", limit = 2)
                binding.tvCongrats.text = arrOfStr[0]
                binding.tvCongrats.setTextColor(
                    ContextCompat.getColor(
                        this@PaymentActivity,
                        R.color.green
                    )
                )
                binding.tvSuccessMessage.text = arrOfStr[1]
            }
        } else {
            if (paymentReQueryResponse.Response.Message.isNotEmpty()) {
                if (paymentReQueryResponse.Response.Message.isNotEmpty()) {
                    binding.tvCongrats.text = paymentReQueryResponse.Response.Status
                    binding.tvCongrats.setTextColor(
                        ContextCompat.getColor(
                            this@PaymentActivity,
                            R.color.red
                        )
                    )
                    binding.tvSuccessMessage.text = paymentReQueryResponse.Response.Message
                }
            }
            binding.tvRetry.visibility = View.VISIBLE
            binding.btnViewOrder.visibility = View.GONE
        }

    }


}