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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import com.android.volley.NoConnectionError
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.ActivityDataPackBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.interactor.ValuePackDetailInteractor
import com.seatel.mobilehall.ui.home.model.MainDataModel
import com.seatel.mobilehall.ui.home.model.ValuePackSectionModel
import com.seatel.mobilehall.ui.home.model.ValuePackTableModel
import com.seatel.mobilehall.ui.home.presenter.ValuePackDetailPresenter
import com.seatel.mobilehall.ui.login.model.ProfileModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView

class DataPackActivity : BaseActivity<ActivityDataPackBinding>(), View.OnClickListener,
    ValuePackDetailInteractor.View {


    private var mSelectPackage = ""
    private var dataMainScreen: MainDataModel? = null
    private var priceMB = ""
    private var durationPlan = 0
    private var amountMB = ""
    private var mTopupAmount = 0.0
    private var mIsForPlan = false
    private var mIsValuePack = false
    private var mIsFortunePack = false
    private var mIsSeatelAirlinePack = false
    private var mIsLanmeiAirlinePack = false
    private var mIsOnlyDisplay = false
    private var mPosition = -1
    private var mPriceDefaultSelect = 0.0

    private var mValuePackDetailPresenter: ValuePackDetailPresenter? = null
    private var mDataValuePack: List<ValuePackTableModel>? = null
    private var indexValuePackSelectItem = -1
    private var mValuePackModel: ValuePackSectionModel? = null
    private var mIsProduct = false
    private val rowData: ArrayList<View> = arrayListOf()

    override fun onClick(v: View?) {

        val type = v?.tag.toString()
        when (type) {
            "binding.item1" -> {
                binding.item1.onSelectItem()
                binding.item2.reset()
                binding.item3.reset()
                binding.item4.reset()
                binding.item5.reset()
                binding.item6.reset()
                if (mIsValuePack) {
                    priceMB = "1"
                    durationPlan = 1
                    amountMB = "$350"
                } else {
                    priceMB = "0.50"
                    durationPlan = 1
                    amountMB = "500MB"
                }
                indexValuePackSelectItem = 0
                resetSelectFlag("1")
            }

            "binding.item2" -> {
                binding.item2.onSelectItem()
                binding.item1.reset()
                binding.item3.reset()
                binding.item4.reset()
                binding.item5.reset()
                binding.item6.reset()
                if (mIsValuePack) {
                    priceMB = "2"
                    durationPlan = 7
                    amountMB = "$550"
                } else {
                    durationPlan = 7
                    priceMB = "1.00"
                    amountMB = "10GB"
                }
                indexValuePackSelectItem = 1
                resetSelectFlag("3")
            }

            "binding.item3" -> {
                binding.item3.onSelectItem()
                binding.item1.reset()
                binding.item2.reset()
                binding.item5.reset()
                binding.item4.reset()
                binding.item6.reset()
                if (mIsValuePack) {
                    priceMB = "5"
                    durationPlan = 30
                    amountMB = "$2000"
                } else {
                    durationPlan = 30
                    priceMB = "5.00"
                    amountMB = "45GB"
                }
                indexValuePackSelectItem = 2
                resetSelectFlag("5")
            }

            "binding.item4" -> {
                binding.item4.onSelectItem()
                binding.item1.reset()
                binding.item2.reset()
                binding.item3.reset()
                binding.item6.reset()
                binding.item5.reset()
                if (mIsValuePack) {
                    priceMB = "8"
                    durationPlan = 30
                    amountMB = "$5550"
                } else {
                    durationPlan = 30
                    priceMB = "10.00"
                    amountMB = "100GB"
                }
                indexValuePackSelectItem = 3
                resetSelectFlag("6")
            }

            else -> {
                mSelectPackage = ""
                durationPlan = 0
                priceMB = "0"
                amountMB = "0"
                indexValuePackSelectItem = -1
                showHideFooterBuySection(false)
            }
        }
        if (mIsForPlan && mTopupAmount < priceMB.toDouble()) {
            SeatelAlertDialog.with(this, getString(R.string.message_internet_pack_bigger_topup))
                .show()
            resetSelect()
        }
    }

    fun checkIsForPlanAction(): Boolean {
        return mIsForPlan
    }

    private fun checkDayStr(strDay: String, dayCount: String): String {
        return when (SeatelUtils.getLangaugeCode(this)) {
            Constant.KHMER, Constant.CHINESE -> {
                "$dayCount$strDay"
            }

            else -> {
                if (dayCount <= 1.toString()) {
                    "$dayCount $strDay"
                } else "$dayCount $strDay" + "s"

            }
        }
    }

    private fun resetSelect() {
        durationPlan = 0
        priceMB = "0"
        amountMB = "0"
        mSelectPackage = ""
        binding.item6.reset()
        binding.item1.reset()
        binding.item2.reset()
        binding.item3.reset()
        binding.item4.reset()
        binding.item5.reset()
        resetSelectFlag("")
    }

    private fun resetSelectFlag(str: String) {
        if (TextUtils.equals(str, mSelectPackage)) {
            mSelectPackage = ""
            priceMB = "0"
            durationPlan = 0
            showHideFooterBuySection(false)
        } else {
            mSelectPackage = str
            showHideFooterBuySection(true)
        }

    }

    private fun showHideFooterBuySection(isShow: Boolean) {
        if (isShow) {
            binding.layoutBgBtnBuy.animate().setDuration(300).translationY(0F)
            binding.layoutBtnBuy.animate().setDuration(440).translationY(0F)
        } else {
            binding.layoutBgBtnBuy.animate().setDuration(300)
                .translationY(binding.layoutBgBtnBuy.height.toFloat())
            binding.layoutBtnBuy.animate().setDuration(440)
                .translationY(binding.layoutBtnBuy.height.toFloat())
        }
    }

    private fun getIndexItemDefaultSelect() {
        when (mPriceDefaultSelect) {
            0.50 -> {
                binding.item1.onSelectItem()
                resetSelectFlag("1")
                durationPlan = 1
                priceMB = "0.50"
                amountMB = "500MB"
            }

            1.0 -> {
                binding.item3.onSelectItem()
                resetSelectFlag("3")
                durationPlan = 7
                priceMB = "1.00"
                amountMB = "10GB"
            }

            5.0 -> {
                binding.item5.onSelectItem()
                resetSelectFlag("5")
                durationPlan = 30
                priceMB = "5.00"
                amountMB = "45GB"
            }

            10.0 -> {
                binding.item6.onSelectItem()
                resetSelectFlag("6")
                durationPlan = 30
                priceMB = "10.00"
                amountMB = "100GB"
            }

            else -> {
                durationPlan = 0
                priceMB = "0"
                amountMB = "0"
            }
        }
        //old version
        /*when (mPriceDefaultSelect) {
            0.10 -> {
                binding.item1.onSelectItem()
                resetSelectFlag("1")
                durationPlan = 1
                priceMB = "0.10"
                amountMB = "500MB"
            }
            0.50 -> {
                binding.item2.onSelectItem()
                resetSelectFlag("2")
                durationPlan = 3
                priceMB = "0.50"
                amountMB = "3GB"
            }
            1.0 -> {
                binding.item3.onSelectItem()
                resetSelectFlag("3")
                durationPlan = 7
                priceMB = "1.00"
                amountMB = "10GB"
            }
            2.0 -> {
                binding.item4.onSelectItem()
                resetSelectFlag("4")
                durationPlan = 7
                priceMB = "2.00"
                amountMB = "20GB"
            }
            5.0 -> {
                binding.item5.onSelectItem()
                resetSelectFlag("5")
                durationPlan = 30
                priceMB = "5.00"
                amountMB = "45GB"
            }
            10.0 -> {
                binding.item6.onSelectItem()
                resetSelectFlag("6")
                durationPlan = 30
                priceMB = "10.00"
                amountMB = "100GB"
            }
            else -> {
                durationPlan = 0
                priceMB = "0"
                amountMB = "0"
            }
        }*/
    }

    private fun showDollarSign() {

       /* binding.item1.tv_sign_dollar.visibility = View.VISIBLE
        binding.item1.tv_size_type.visibility = View.GONE
        binding.item2.tv_sign_dollar.visibility = View.VISIBLE
        binding.item2.tv_size_type.visibility = View.GONE
        binding.item3.tv_sign_dollar.visibility = View.VISIBLE
        binding.item3.tv_size_type.visibility = View.GONE
        binding.item4.tv_sign_dollar.visibility = View.VISIBLE
        binding.item4.tv_size_type.visibility = View.GONE*/

    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterRightAnimation()
        //    setContentView(R.layout.activity_data_pack)
        //   FirebaseAnalyticsUtil.getInstance(this).logCustomEvent(Constant.SeaTelAnalytics.Value.GET_INTERNET_PACK)

//        binding.row1.visibility = View.INVISIBLE
//        binding.row2.visibility = View.INVISIBLE
//        binding.viewDescriptionValuePack.visibility = View.GONE


        mIsValuePack = intent.getBooleanExtra("IS_VALUE_PACK", false)
        mIsFortunePack = intent.getBooleanExtra("FORTUNE_PACK", false)
        mIsSeatelAirlinePack = intent.getBooleanExtra("SEATEL_AIRLINE_PACK", false)
        mIsLanmeiAirlinePack = intent.getBooleanExtra("LANMEI_AIRLINE_PACK", false)
        mIsOnlyDisplay = intent.getBooleanExtra("ONLY_DISPLAY", true)
        mIsProduct = intent.getBooleanExtra("IS_PRODUCT", false)

        if (mIsValuePack) {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            mValuePackDetailPresenter = ValuePackDetailPresenter(this)
            mValuePackDetailPresenter?.onLoadValuePack()
            showDollarSign()
            binding.valuePackTitle.visibility = View.VISIBLE
            binding.row1.visibility = View.GONE
            binding.row2.visibility = View.GONE
        }

        if (mIsFortunePack) {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            mValuePackDetailPresenter = ValuePackDetailPresenter(this)
            mValuePackDetailPresenter?.onLoadFortunePack()
            showDollarSign()
            binding.valuePackTitle.visibility = View.VISIBLE
            binding.row1.visibility = View.GONE
            binding.row2.visibility = View.GONE
        }

        if (mIsSeatelAirlinePack) {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            mValuePackDetailPresenter = ValuePackDetailPresenter(this)
            mValuePackDetailPresenter?.onLoadSeatelAirlinePack()
            showDollarSign()
            binding.valuePackTitle.visibility = View.VISIBLE
            binding.row1.visibility = View.GONE
            binding.row2.visibility = View.GONE
        }
        if (mIsLanmeiAirlinePack) {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            mValuePackDetailPresenter = ValuePackDetailPresenter(this)
            mValuePackDetailPresenter?.onLoadLanmeiAirlinePack()
            showDollarSign()
            binding.valuePackTitle.visibility = View.VISIBLE
            binding.row1.visibility = View.GONE
            binding.row2.visibility = View.GONE
        }

        if (mIsOnlyDisplay) {
            binding.row1.visibility = View.GONE
            binding.row2.visibility = View.GONE
            binding.valuePackTitle.visibility = View.GONE
            val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            params.setMargins(10, 10, 0, 20)
            binding.valuePackSubTitle.layoutParams = params
            binding.valuePackSubTitle.textAlignment = View.TEXT_ALIGNMENT_TEXT_START
            binding.valuePackSubTitle.text =
                "Enjoy the internet with the best 4G xperience no matter where you are in Cambodia by dial the USSD code in the table below:"
        }

        if (intent.hasExtra("is_for_plan"))
            mIsForPlan = intent.getBooleanExtra("is_for_plan", false)
        if (intent.hasExtra("topup_amount"))
            mTopupAmount = intent.getDoubleExtra("topup_amount", 0.0)
        if (intent.hasExtra(Constant.ADD_ON_POSITION))
            mPosition = intent.getIntExtra(Constant.ADD_ON_POSITION, -1)
        if (intent.hasExtra(Constant.PRICE_VALUE))
            mPriceDefaultSelect = intent.getDoubleExtra(Constant.PRICE_VALUE, 0.0)

        if (mIsForPlan) {
            binding.btnBuy.text = "Done"
            binding.layoutTop.visibility = View.GONE
        }

        if (isNoneSeatel()) {
            if (SeatelSharePreferences.getInstance(this)?.getUserInfo()?.isNotEmpty()!!) {
                val mDataProfile = Gson().fromJson<ProfileModel>(
                    SeatelSharePreferences.getInstance(this)?.getUserInfo(),
                    ProfileModel::class.java
                )
                if (mDataProfile != null) {
                    binding.ctvUserName.text =
                        if (mDataProfile.custName.isEmpty()) "N/A" else mDataProfile.custName
                    binding.ctvPhoneNumber.text = SeatelUtils.phoneNumberFormat(mDataProfile.msisdn)
                }
            }
        } else {
            if (SeatelSharePreferences.getInstance(this)?.getMainPhoneLogin()?.isNotEmpty()!!) {
                dataMainScreen = Gson().fromJson<MainDataModel>(
                    SeatelSharePreferences.getInstance(this)?.getMainScreenData(),
                    MainDataModel::class.java
                )
                if (dataMainScreen != null) {
                    binding.ctvUserName.text = dataMainScreen?.getCustName()
                    binding.ctvPhoneNumber.text =
                        SeatelUtils.phoneNumberFormat(dataMainScreen?.getPhonNumber())
                }
            }
        }

        var dayStr = SeatelUtils.translatForDialog(this, "Day")
        binding.item1.setValueData("0.50", "500", checkDayStr(dayStr, "1"), "MB")
        binding.item2.setValueData("1", "10", checkDayStr(dayStr, "7"), "GB")
        binding.item3.setValueData("5", "45", checkDayStr(dayStr, "30"), "GB")
        binding.item4.setValueData("10", "100", checkDayStr(dayStr, "30"), "GB")

        //old version
        /*binding.item1.setValueData("0.10", "500", checkDayStr(dayStr,"1"), "MB", false)
        binding.item2.setValueData("0.50", "3", checkDayStr(dayStr,"3"), "GB", false)
        binding.item3.setValueData("1", "10", checkDayStr(dayStr,"7"), "GB", true)
        binding.item4.setValueData("2", "20", checkDayStr(dayStr,"7"), "GB", true)
        binding.item5.setValueData("5", "45", checkDayStr(dayStr,"30"), "GB", false)
        binding.item6.setValueData("10", "100", checkDayStr(dayStr,"30"), "GB", false)*/

        binding.item1.setOnClickListener(this)
        binding.item2.setOnClickListener(this)
        binding.item3.setOnClickListener(this)
        binding.item4.setOnClickListener(this)
//        binding.item5.setOnClickListener(this)
//        binding.item6.setOnClickListener(this)


        if (mPriceDefaultSelect > 0.0 && !mIsValuePack && !mIsFortunePack && !mIsLanmeiAirlinePack)
            getIndexItemDefaultSelect()



        binding.btnBuy.setOnClickListener {
            when {
                mIsForPlan -> onBackPressed()
                mIsValuePack -> mDataValuePack?.get(indexValuePackSelectItem)
                    ?.let { it1 -> ConfirmBuyDataPackActivity.lunchFromValuePack(this, it1, "") }

                else -> ConfirmBuyDataPackActivity.lunchFromDataPack(
                    this,
                    amountMB,
                    priceMB,
                    binding.ctvPhoneNumber.text.toString(),
                    durationPlan,
                    false,
                    ""
                )
            }
        }


        if (mIsValuePack || mIsOnlyDisplay || mIsFortunePack || mIsLanmeiAirlinePack) {
            rowData.add(binding.viewDescriptionValuePack)
        } /*else {
            rowData.add(binding.row1)
            rowData.add(binding.row2)
        }*/
        //rowData.add(row3)
        rowData.add(binding.viewFooterTab)
        for (i in 0 until rowData.size) {
            Handler().postDelayed({
                rowData[i].visibility = View.VISIBLE
                val animation = AnimationUtils.loadAnimation(
                    rowData[i].context,
                    R.anim.anim_recycler_item
                ) as Animation
                rowData[i].startAnimation(animation)
            }, 800)
        }

        binding.row1.visibility = View.GONE
        binding.row2.visibility = View.GONE
        binding.viewDescriptionValuePack.visibility = View.VISIBLE
    }

    private fun setDataTitleDescriptionValuePack(valuePackSectionModel: ValuePackSectionModel) {
        binding.valuePackTitle.text = valuePackSectionModel.valuePackSecTwoModel.title
        binding.valuePackSubTitle.text = valuePackSectionModel.valuePackSecTwoModel.subTitle
    }


    override fun onResponseValuePackSucceed(valuePackSectionModel: ValuePackSectionModel) {
        mValuePackModel = valuePackSectionModel
        getData()
        mDataValuePack = valuePackSectionModel.valuePackSecTwoModel.table
        binding.viewFooterTab.setDataValuePackFooter(
            valuePackSectionModel,
            valuePackSectionModel.valuePackSecThreeModel.description,
            true
        )
        setDataTitleDescriptionValuePack(valuePackSectionModel)
        binding.errorView.visibility = View.GONE
    }

    override fun onResponseFailed(error: VolleyError) {
        when (error) {
            is TimeoutError -> {
                binding.errorView.errorMessage = getString(R.string.connection_timeout)
                binding.errorView.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }

            is NoConnectionError -> {
                binding.errorView.errorMessage = getString(R.string.message_no_internet)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }

            else -> {
                binding.errorView.errorMessage = getString(R.string.connection_timeout)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
            }
        }
    }

    fun getData(): ValuePackSectionModel? {
        return mValuePackModel
    }


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

    fun setDataValuePackResultForPlanSelect(price: String, duration: Int) {
        if (price.isNotEmpty() && mIsForPlan && mTopupAmount < price.toDouble()) {
            SeatelAlertDialog.with(this, getString(R.string.message_value_pack_bigger_topup)).show()
            return
        }

        priceMB = price
        durationPlan = duration
        onBackPressed()
    }

    private fun setResultBack() {
        val intent = Intent()
        intent.putExtra(
            Constant.INTERNET_PACK_PRICE_SELECT,
            if (priceMB.isEmpty()) 0.0 else priceMB.toDouble()
        )
        intent.putExtra(Constant.ADD_ON_DURACTION, durationPlan)
        intent.putExtra(Constant.ADD_ON_POSITION, mPosition)
        setResult(Activity.RESULT_OK, intent)
    }

    companion object {
        fun lunch(
            context: Context,
            isValuePack: Boolean = false,
            onlyDisplay: Boolean = false,
            isFortunePack: Boolean = false,
            isProduct: Boolean = false,
            isSeatelAirline: Boolean = false,
            isLanmeiAirline: Boolean = false
        ) {
            val intent = Intent(context, DataPackActivity::class.java)
            intent.putExtra("IS_VALUE_PACK", isValuePack)
            intent.putExtra("FORTUNE_PACK", isFortunePack)
            intent.putExtra("SEATEL_AIRLINE_PACK", isSeatelAirline)
            intent.putExtra("LANMEI_AIRLINE_PACK", isLanmeiAirline)
            intent.putExtra("ONLY_DISPLAY", onlyDisplay)
            intent.putExtra("IS_PRODUCT", isProduct)
            context.startActivity(intent)
        }

        fun lunchForResult(
            context: Context,
            isForPlan: Boolean = false,
            topupAmount: Double = 0.0,
            position: Int,
            priceSelect: Double,
            isValuePack: Boolean = false
        ) {
            val intent = Intent(context, DataPackActivity::class.java)
            intent.putExtra("is_for_plan", isForPlan)
            intent.putExtra("topup_amount", topupAmount)
            intent.putExtra("IS_VALUE_PACK", isValuePack)
            intent.putExtra(Constant.ADD_ON_POSITION, position)
            intent.putExtra(Constant.PRICE_VALUE, priceSelect)
            (context as Activity).startActivityForResult(intent, Constant.PLAN_SUBSCRIPTION)
        }
    }

    override fun onBackPressed() {
        if (mIsForPlan)
            setResultBack()
        super.onBackPressed()
        activityExitLeftAnimation()
    }

    override fun getToolbarTitle(): String {
        return when {
            intent.getBooleanExtra(
                "IS_VALUE_PACK",
                false
            ) -> resources.getString(R.string.value_pack)

            intent.getBooleanExtra(
                "FORTUNE_PACK",
                false
            ) -> resources.getString(R.string.fortune_pack)

            intent.getBooleanExtra(
                "SEATEL_AIRLINE_PACK",
                false
            ) -> resources.getString(R.string.seatel_airline)

            intent.getBooleanExtra(
                "LANMEI_AIRLINE_PACK",
                false
            ) -> resources.getString(R.string.lanmei_airline)

            else -> resources.getString(R.string.data_pack_title)
        }
    }
}
