package com.seatel.mobilehall.ui.profile.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import coil.load
import coil.transform.CircleCropTransformation
import com.android.volley.NoConnectionError
import com.android.volley.Request
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.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.FragmentProfileBinding
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.model.MainDataModel
import com.seatel.mobilehall.ui.login.activity.LoginActivity
import com.seatel.mobilehall.ui.profile.activity.ProfileActivity
import com.seatel.mobilehall.ui.profile.activity.SettingActivity
import com.seatel.mobilehall.ui.profile.adapter.MySubscriptionAdapter
import com.seatel.mobilehall.ui.profile.interactor.MySubScriptionInteractor
import com.seatel.mobilehall.ui.profile.interactor.RequestSlideAccountUserNameInteractor
import com.seatel.mobilehall.ui.profile.model.MySubscriptionModel
import com.seatel.mobilehall.ui.profile.presenter.MySubscriptionPresenter
import com.seatel.mobilehall.ui.profile.presenter.SlideAccountUserNamePresenter
import com.seatel.mobilehall.util.AnalyticsHelper
import com.seatel.mobilehall.util.BottomAccountChooserDialog
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.request.GetMainData
import com.seatel.mobilehall.util.viewFragmentBinding
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

class ProfilesFragment : BaseFragment(), RequestSlideAccountUserNameInteractor.View,
    MySubScriptionInteractor.View, SwipeRefreshLayout.OnRefreshListener {

    private val TAG = ProfilesFragment::class.java.toString()

    private val binding by viewFragmentBinding(
        FragmentProfileBinding::inflate
    )

    private var dataMainScreen: MainDataModel? = null
    private lateinit var mSlideAccountUserNamePresenter: SlideAccountUserNamePresenter
    private var mDataAccountName: ArrayList<BottomAccountChooserDialog.BottomAccountChooserModel>? =
        null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        init()
        return binding.root
    }

    private fun init() {
        loginCheck()
        setupClick()
    }

    private fun setupClick() {
        binding.run {
            ivSetting.setOnClickListener {
                AnalyticsHelper.logEvent(
                    AnalyticsHelper.Event.PROFILE_TAP_SETTING,
                    null
                )
                SettingActivity.lunch(getmContext())
            }

            tvLoginSignUp.setOnClickListener {
                LoginActivity.lunch(requireContext())
            }

            ivProfile.setOnClickListener {

                AnalyticsHelper.logEvent(
                    AnalyticsHelper.Event.PROFILE_TAP_PROFILE_PICTURE,
                    null
                )
                if (getMainPhoneLogin().isEmpty() || getPhoneLogin().isEmpty()) {
                    LoginActivity.lunch(requireContext())
                } else
                    ProfileActivity.lunch(getmContext())
            }

        }


    }

    private fun loginCheck() {
        binding.run {
            if (getPhoneLogin().isEmpty() || getMainPhoneLogin().isEmpty()) {
                // not login
                binding.mSwipeRefreshLayout.visibility = View.GONE
                tvLoginSignUp.visibility = View.VISIBLE
                layoutParentProfile.visibility = View.GONE
            } else {
                binding.mSwipeRefreshLayout.visibility = View.VISIBLE
                tvLoginSignUp.visibility = View.GONE
                layoutParentProfile.visibility = View.VISIBLE
                setupProfile()
                MySubscriptionPresenter(getmContext(), this@ProfilesFragment).onLoadData(
                    getPhoneLogin()
                )
                mSlideAccountUserNamePresenter =
                    SlideAccountUserNamePresenter(requireContext(), this@ProfilesFragment)
                mSlideAccountUserNamePresenter.onRequestSlideAccount(getMainPhoneLogin())
                binding.mSwipeRefreshLayout.setOnRefreshListener(this@ProfilesFragment)
                binding.mSwipeRefreshLayout.setColorSchemeColors(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.colorPrimary
                    )
                )
            }
        }
    }

    private fun setupProfile() {
        GetMainData(getmContext(), getPhoneLogin(), "") { it ->
            if (it) {
                dataMainScreen = Gson().fromJson(
                    context?.let { it1 ->
                        SeatelSharePreferences.getInstance(it1)?.getMainScreenData()
                    },
                    MainDataModel::class.java
                )
                dataMainScreen?.let {
                    binding.run {
                        tvUsername.text = it.getCustName()
                        tvPhoneNumber.text = it.getPhonNumber()
                        viewSubNumber.visibility = View.VISIBLE
                        ivProfile.load(it.getProfilePicture()) {
                            crossfade(true)
                            transformations(CircleCropTransformation())
                            error(R.drawable.ic_yes_profile)
                            placeholder(R.drawable.ic_yes_profile)
                        }

                        layoutViewSubNumber.setOnClickListener {
                            setupViewSubNum()
                        }
                    }

                }
            }

        }.execute()
    }

    private fun setupViewSubNum() {
        if (mDataAccountName != null && mDataAccountName?.size!! > 0) {
            BottomAccountChooserDialog(requireContext()).addItems(
                mDataAccountName!!,
                object : BottomAccountChooserDialog.OnItemChooser {
                    override fun onChose(
                        position: Int,
                        data: BottomAccountChooserDialog.BottomAccountChooserModel
                    ) {
                        if (position == mDataAccountName?.size!! - 1) {
                            LoginActivity.launchWithAddNewPhone(getmContext())
                        } else {
                            SeatelSharePreferences.getInstance(requireContext())
                                ?.setPhoneLogin(data.name)
                            binding.run {
                                tvUsername.text = data.id
                                tvPhoneNumber.text = data.name
                            }
                            setupProfile()
                            MySubscriptionPresenter(
                                getmContext(),
                                this@ProfilesFragment
                            ).onLoadData(getPhoneLogin())
                        }
                    }

                    override fun onDelete(
                        position: Int,
                        data: BottomAccountChooserDialog.BottomAccountChooserModel
                    ) {
                        SeatelAlertDialog.with(
                            requireContext(), getString(R.string.message_delete_number)
                        ).setCancelable(true)
                            .setNegativeButton(getString(R.string.no)) { dai, _ ->
                                dai.dismiss()
                            }.setPositiveButton(getString(R.string.yes)) { _, _ ->
                                deletedAccountUnLinkedNumber(data.name)
                            }.show()
                    }

                }).show()
        }
    }

    private fun deletedAccountUnLinkedNumber(phoneNumberDelete: String) {

        object : SeatelJSONObjectRequest(requireContext()) {
            override fun getFunctionName(): String {
                return if (phoneNumberDelete.isNotEmpty()) "users/${getMainPhoneLogin()}/unlinked-phone-number" else ""
            }

            override fun getMethod(): Int {
                return Request.Method.PUT
            }

            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                try {
                    val numberDeleted = JSONArray()
                    numberDeleted.put(phoneNumberDelete)
                    data.put("unlinkedPhoneNumbers", numberDeleted)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                return data.toString()
            }

        }.setOnErrorListener {
            SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(it))
                .show()

        }.execute {
            it as JSONObject
            if (it.has("message"))
                if (it.optString("message").toLowerCase() == "ok") {
                    SeatelSharePreferences.getInstance(requireContext())
                        ?.setPhoneLogin(getMainPhoneLogin())
                    mSlideAccountUserNamePresenter.onRequestSlideAccount(getMainPhoneLogin())
                    setupProfile()
                    MySubscriptionPresenter(getmContext(), this).onLoadData(getPhoneLogin())
                }
        }

    }

    override fun onRequestSlideAccountSuccess(response: JSONArray) {
        if (response.length() > 0) {
            mDataAccountName = ArrayList<BottomAccountChooserDialog.BottomAccountChooserModel>()
            for (i in 0 until response.length()) {
                var isDeleted = true
                if (i == 0)
                    isDeleted = false
                mDataAccountName?.add(
                    BottomAccountChooserDialog.BottomAccountChooserModel(
                        response.optJSONObject(i).optString("custName"),
                        response.optJSONObject(i).optString("mSISDN"),
                        isDeleted
                    )
                )

            }
            // Add new number data
            mDataAccountName?.add(
                BottomAccountChooserDialog.BottomAccountChooserModel(
                    "Add Phone Number",
                    "Add Phone Number",
                    false
                )
            )
        }
        MyApplication.isAddnewNumberDone = false
    }

    override fun onRequestSlideAccountFailed(error: VolleyError) {

    }

    override fun onLoadDataSucceed(mySubscriptionModel: MySubscriptionModel) {
        super.onLoadDataSucceed(mySubscriptionModel)
        binding.errorView.visibility = View.GONE
        if (context != null) {
            binding.recyclerViewMySubscription.adapter = MySubscriptionAdapter(
                getmContext(),
                mySubscriptionModel,
                SeatelSharePreferences.getInstance(getmContext())?.getIsPostPaid()
            )
        }
        binding.mSwipeRefreshLayout.isRefreshing = false
    }

    override fun onLoadDataFailed(error: VolleyError) {
        super.onLoadDataFailed(error)
        binding.mSwipeRefreshLayout.isRefreshing = false
        binding.run {
            when (error) {
                is TimeoutError -> {
                    errorView.errorMessage = getString(R.string.connection_timeout)
                    errorView.setViewMode(ErrorHandleView.Mode.TIME_OUT)
                }

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

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

    }

    override fun onResume() {
        super.onResume()
        if (MyApplication.isAddnewNumberDone) {
            mSlideAccountUserNamePresenter.onRequestSlideAccount(getMainPhoneLogin())
        }
        init()
    }

    override fun onRefresh() {
        MySubscriptionPresenter(getmContext(), this@ProfilesFragment).onLoadData(
            getPhoneLogin()
        )
    }

}