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.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
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.google.gson.Gson
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_data_pack.*
import kotlinx.android.synthetic.main.view_item_data_pack.view.*

class DataPackActivity : BaseActivity(), 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) {
            "item1" -> {
                item1.onSelectItem()
                item2.reset()
                item3.reset()
                item4.reset()
                item5.reset()
                item6.reset()
                if (mIsValuePack) {
                    priceMB = "1"
                    durationPlan = 1
                    amountMB = "$350"
                } else {
                    priceMB = "0.50"
                    durationPlan = 1
                    amountMB = "500MB"
                }
                indexValuePackSelectItem = 0
                resetSelectFlag("1")
            }
            "item2" -> {
                item2.onSelectItem()
                item1.reset()
                item3.reset()
                item4.reset()
                item5.reset()
                item6.reset()
                if (mIsValuePack) {
                    priceMB = "2"
                    durationPlan = 7
                    amountMB = "$550"
                } else {
                    durationPlan = 7
                    priceMB = "1.00"
                    amountMB = "10GB"
                }
                indexValuePackSelectItem = 1
                resetSelectFlag("3")
            }
            "item3" -> {
                item3.onSelectItem()
                item1.reset()
                item2.reset()
                item5.reset()
                item4.reset()
                item6.reset()
                if (mIsValuePack) {
                    priceMB = "5"
                    durationPlan = 30
                    amountMB = "$2000"
                } else {
                    durationPlan = 30
                    priceMB = "5.00"
                    amountMB = "45GB"
                }
                indexValuePackSelectItem = 2
                resetSelectFlag("5")
            }
            "item4" -> {
                item4.onSelectItem()
                item1.reset()
                item2.reset()
                item3.reset()
                item6.reset()
                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 = ""
        item6.reset()
        item1.reset()
        item2.reset()
        item3.reset()
        item4.reset()
        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) {
            layout_bg_btn_buy.animate().setDuration(300).translationY(0F)
            layout_btn_buy.animate().setDuration(440).translationY(0F)
        } else {
            layout_bg_btn_buy.animate().setDuration(300)
                .translationY(layout_bg_btn_buy.height.toFloat())
            layout_btn_buy.animate().setDuration(440).translationY(layout_btn_buy.height.toFloat())
        }
    }

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

    private fun showDollarSign() {
        item1.tv_sign_dollar.visibility = View.VISIBLE
        item1.tv_size_type.visibility = View.GONE
        item2.tv_sign_dollar.visibility = View.VISIBLE
        item2.tv_size_type.visibility = View.GONE
        item3.tv_sign_dollar.visibility = View.VISIBLE
        item3.tv_size_type.visibility = View.GONE
        item4.tv_sign_dollar.visibility = View.VISIBLE
        item4.tv_size_type.visibility = View.GONE
    }

    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)

//        row1.visibility = View.INVISIBLE
//        row2.visibility = View.INVISIBLE
//        view_description_value_pack.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) {
            error_view.setViewMode(ErrorHandleView.Mode.LOADING)
            mValuePackDetailPresenter = ValuePackDetailPresenter(this)
            mValuePackDetailPresenter?.onLoadValuePack()
            showDollarSign()
            value_pack_title.visibility = View.VISIBLE
            row1.visibility = View.GONE
            row2.visibility = View.GONE
        }

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

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

        if (mIsOnlyDisplay) {
            row1.visibility = View.GONE
            row2.visibility = View.GONE
            value_pack_title.visibility = View.GONE
            val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            params.setMargins(10, 10, 0, 20)
            value_pack_sub_title.layoutParams = params
            value_pack_sub_title.textAlignment = View.TEXT_ALIGNMENT_TEXT_START
            value_pack_sub_title.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) {
            btn_buy.text = "Done"
            layout_top.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) {
                    ctv_user_name.text =
                        if (mDataProfile.custName.isEmpty()) "N/A" else mDataProfile.custName
                    ctv_phone_number.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) {
                    ctv_user_name.text = dataMainScreen?.getCustName()
                    ctv_phone_number.text =
                        SeatelUtils.phoneNumberFormat(dataMainScreen?.getPhonNumber())
                }
            }
        }

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

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

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


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



        btn_buy.setOnClickListener {
            when {
                mIsForPlan -> onBackPressed()
                mIsValuePack -> mDataValuePack?.get(indexValuePackSelectItem)
                    ?.let { it1 -> ConfirmBuyDataPackActivity.lunchFromValuePack(this, it1, "") }
                else -> ConfirmBuyDataPackActivity.lunchFromDataPack(
                    this,
                    amountMB,
                    priceMB,
                    ctv_phone_number.text.toString(),
                    durationPlan,
                    false,
                    ""
                )
            }
        }


        if (mIsValuePack || mIsOnlyDisplay || mIsFortunePack || mIsLanmeiAirlinePack) {
            rowData.add(view_description_value_pack)
        } /*else {
            rowData.add(row1)
            rowData.add(row2)
        }*/
        //rowData.add(row3)
        rowData.add(view_footer_tab)
        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)
        }

        row1.visibility = View.GONE
        row2.visibility = View.GONE
        view_description_value_pack.visibility = View.VISIBLE
    }

    private fun setDataTitleDescriptionValuePack(valuePackSectionModel: ValuePackSectionModel) {
        value_pack_title.text = valuePackSectionModel.valuePackSecTwoModel.title
        value_pack_sub_title.text = valuePackSectionModel.valuePackSecTwoModel.subTitle
    }


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

    override fun onResponseFailed(error: VolleyError) {
        when (error) {
            is TimeoutError -> {
                error_view.errorMessage = getString(R.string.connection_timeout)
                error_view.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }
            is NoConnectionError -> {
                error_view.errorMessage = getString(R.string.message_no_internet)
                error_view.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }
            else -> {
                error_view.errorMessage = getString(R.string.connection_timeout)
                error_view.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)
        }
    }
}
