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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LayoutAnimationController
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.NoConnectionError
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.paginate.Paginate
import com.paginate.recycler.LoadingListItemSpanLookup
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.databinding.ActivitySupportListBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.FAQsAdapter
import com.seatel.mobilehall.ui.home.adapter.SupportListAdapter
import com.seatel.mobilehall.ui.home.adapter.SupportedDeviceDetailAdapter
import com.seatel.mobilehall.ui.home.interactor.FAQsInteractor
import com.seatel.mobilehall.ui.home.interactor.ItemViewInteractor
import com.seatel.mobilehall.ui.home.interactor.SupportedDeviceInteractor
import com.seatel.mobilehall.ui.home.model.FAQModel
import com.seatel.mobilehall.ui.home.model.SupportedDeviceModel
import com.seatel.mobilehall.ui.home.presenter.FAQsPresenter
import com.seatel.mobilehall.ui.home.presenter.SupportedDevicePresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView


class SupportListActivity : BaseActivity<ActivitySupportListBinding>(),
    SupportedDeviceInteractor.View, ItemViewInteractor,
    View.OnClickListener, FAQsInteractor.View {

    private lateinit var presenter: SupportedDeviceInteractor.Presenter
    private var supportedDeviceList: ArrayList<SupportedDeviceModel> = ArrayList()
    private val animId = R.anim.layout_slide_from_bottom
    private lateinit var animation: LayoutAnimationController
    private var supportedDeviceDetailList: ArrayList<String> = ArrayList()
    private var isSearchName = false
    private var isSupportedDevice = false
    private var isFaq = false
    private var offset = 0
    private var LIMIT_OFF_SET = 10
    private lateinit var faqsPresenter: FAQsPresenter
    private lateinit var supportLisAdapter: SupportListAdapter
    private lateinit var supportedDeviceDetailAdapter: SupportedDeviceDetailAdapter
    private lateinit var faqAdapter: FAQsAdapter
    private lateinit var faqList: ArrayList<FAQModel>
    private var isLoading = false
    private var isLoadAll = false
    private lateinit var paginate: Paginate
    override fun getViewBinding(): ActivitySupportListBinding {
        return ActivitySupportListBinding.inflate(layoutInflater)
    }

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

    override fun responseSucceedSupportedDeviceData(supportedDeviceList: ArrayList<SupportedDeviceModel>) {

        this.supportedDeviceList.clear()
        this.supportedDeviceList.addAll(supportedDeviceList)
        supportLisAdapter = SupportListAdapter(this, this.supportedDeviceList, this)
        binding.rvSupportList.adapter = supportLisAdapter
        hideProgress()
        /*paginate.unbind()
        paginate.setHasMoreDataToLoad(false)*/
    }

    override fun responseFailed(error: VolleyError) {
        paginate.setHasMoreDataToLoad(false)
        hideProgress()
        binding.rvSupportList.visibility = View.GONE
        binding.errorView.visibility = View.VISIBLE
        when (error) {
            is NoConnectionError -> {
                binding.errorView.errorMessage = getString(R.string.connection_timeout)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_INTERNET)
            }

            is TimeoutError -> {
                binding.errorView.errorMessage = getString(R.string.fetch_supported_device_data)
                binding.errorView.setViewMode(ErrorHandleView.Mode.TIME_OUT)
            }

            else -> {
                binding.errorView.errorMessage = SeatelSuperRequest.getErrorMessageFrom(error)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
            }
        }
    }

    fun getFAQsDefaultList() {
        faqList.clear()
        faqAdapter.notifyDataSetChanged()
        faqsPresenter.onLoadData("", 0)


    }

    private fun init() {

        val titleToolBar: String =
            intent.getStringExtra(Constant.SUPPORT_IDENTIFY).toString()
        setUpToolbarTitle(titleToolBar)

        binding.imageClear.setOnClickListener(this)
        animation = AnimationUtils.loadLayoutAnimation(this, animId)
        binding.rvSupportList.layoutManager = LinearLayoutManager(this)
        binding.rvSupportList.layoutAnimation = animation
        supportedDeviceDetailList =
            intent.getStringArrayListExtra(Constant.SUPPORTED_DEVICE_DETAIL)!!
        faqsPresenter = FAQsPresenter(this)


        //faq recycler view staff
        faqList = ArrayList()
        faqAdapter = FAQsAdapter(this, faqList)
        binding.rvSupportList.layoutManager = LinearLayoutManager(this@SupportListActivity)
        binding.rvSupportList.layoutAnimation = this@SupportListActivity.animation
        binding.rvSupportList.adapter = faqAdapter


        if (supportedDeviceDetailList.size == 0) {

            if (titleToolBar == Constant.EXTRA_FAQ) {
                getFAQsDefaultList()
                isFaq = true
                paginate = Paginate.with(binding.rvSupportList, callbacks)
                    .setLoadingTriggerThreshold(2)
                    .addLoadingListItem(true)
                    .setLoadingListItemCreator(null)
                    .setLoadingListItemSpanSizeLookup(LoadingListItemSpanLookup { 5 })
                    .build()
            } else {
                presenter = SupportedDevicePresenter(this)
                presenter.onLoadData()
                isSupportedDevice = true
                showProgress()
            }

        } else {
            supportedDeviceDetailAdapter =
                SupportedDeviceDetailAdapter(this, supportedDeviceDetailList)
            binding.rvSupportList.adapter = supportedDeviceDetailAdapter
            isSearchName = true
            isSupportedDevice = true
        }
        onSearchAndAnimateEdittext()

        /*paginate = Paginate.with(binding.rvSupportList, callbacks)
                .setLoadingTriggerThreshold(2)
                .addLoadingListItem(true)
                .setLoadingListItemCreator(null)
                .setLoadingListItemSpanSizeLookup(LoadingListItemSpanLookup { 5 })
                .build()*/
        //paginate.setHasMoreDataToLoad(!intent.getBooleanExtra(Constant.IntentKeys.SEARCH_DEVICE, false))

    }

    private var callbacks: Paginate.Callbacks = object : Paginate.Callbacks {
        override fun onLoadMore() {
            if (this@SupportListActivity.isLoading) {
                offset += LIMIT_OFF_SET
                faqsPresenter.onLoadData("", offset)
                this@SupportListActivity.isLoading = false

            }
        }

        override fun isLoading(): Boolean {
            // Indicate whether new page loading is in progress or not
            return false
        }

        override fun hasLoadedAllItems(): Boolean {
            // Indicate whether all data (pages) are loaded or not
            return isLoading
        }

    }
    var a = 1
    private fun onSearchAndAnimateEdittext() {
        binding.cetSearch.apply {
            onFocusChangeListener = View.OnFocusChangeListener { _, _ ->
                animateSearch()

                addTextChangedListener(object : TextWatcher {
                    override fun afterTextChanged(s: Editable?) {}

                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        string: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        if (TextUtils.isEmpty(string)) {
                            binding.imageClear.visibility = View.INVISIBLE
                            binding.fakeHint.visibility = View.VISIBLE
                            binding.errorView.visibility = View.GONE

                            if (isSearchName && isSupportedDevice) {
                                binding.rvSupportList.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                binding.rvSupportList.layoutAnimation =
                                    this@SupportListActivity.animation
                                supportedDeviceDetailAdapter = SupportedDeviceDetailAdapter(
                                    applicationContext,
                                    supportedDeviceDetailList
                                )
                                binding.rvSupportList.adapter = supportedDeviceDetailAdapter
                            } else if (isFaq) {
                                getFAQsDefaultList()
                            } else if (isSupportedDevice) {
                                binding.rvSupportList.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                binding.rvSupportList.layoutAnimation =
                                    this@SupportListActivity.animation
                                supportLisAdapter = SupportListAdapter(
                                    applicationContext,
                                    supportedDeviceList,
                                    this@SupportListActivity
                                )
                                binding.rvSupportList.adapter = supportLisAdapter
                            }

                        } else {
                            binding.fakeHint.visibility = View.INVISIBLE
                            binding.imageClear.visibility = View.VISIBLE

                            //search supported device by name
                            if (isSearchName && isSupportedDevice) {
                                val searchSupportedDeviceDetail = ArrayList<String>()
                                supportedDeviceDetailList.forEach {
                                    if (it.toLowerCase().contains(string.toString())) {
                                        searchSupportedDeviceDetail.add(it)
                                    }
                                }
                                if (searchSupportedDeviceDetail.isEmpty()) {
                                    binding.errorView.visibility = View.VISIBLE
                                    binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
                                } else binding.errorView.visibility = View.GONE
                                binding.rvSupportList.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                binding.rvSupportList.layoutAnimation =
                                    this@SupportListActivity.animation
                                supportedDeviceDetailAdapter = SupportedDeviceDetailAdapter(
                                    applicationContext,
                                    searchSupportedDeviceDetail
                                )
                                binding.rvSupportList.adapter = supportedDeviceDetailAdapter

                            }
                            //search supported device by brand
                            else if (isSupportedDevice) {
                                val searchSupportDevice = ArrayList<SupportedDeviceModel>()
                                supportedDeviceList.forEach {
                                    if (it.brand?.toLowerCase()!!.contains(string.toString())) {
                                        searchSupportDevice.add(it)
                                    }
                                }
                                if (searchSupportDevice.isEmpty()) {
                                    binding.errorView.visibility = View.VISIBLE
                                    binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
                                } else binding.errorView.visibility = View.GONE
                                binding.rvSupportList.layoutManager =
                                    LinearLayoutManager(this@SupportListActivity)
                                binding.rvSupportList.layoutAnimation =
                                    this@SupportListActivity.animation
                                supportLisAdapter = SupportListAdapter(
                                    applicationContext,
                                    searchSupportDevice,
                                    this@SupportListActivity
                                )
                                binding.rvSupportList.adapter = supportLisAdapter
                            } else if (isFaq) {
                                offset = 0
                                faqList.clear()
                                faqAdapter.notifyDataSetChanged()
                                faqsPresenter.onLoadData(string.toString(), offset)
                            }
                        }
                    }
                })
            }
        }
    }

    override fun responseSucceedFAQsData(faqList: ArrayList<FAQModel>, totalCount: Int) {

        this.faqList.addAll(faqList)
        faqAdapter.notifyItemChanged(this.faqList.size - faqList.size)


        if (faqList.isEmpty() || totalCount <= this.faqList.size || totalCount <= faqList.size) {
            isLoadAll = true
            isLoading = false
            paginate.unbind()
            paginate.setHasMoreDataToLoad(false)

        } else {
            isLoadAll = false
            isLoading = true


        }


        //check is data empty
        if (this.faqList.size == 0) {
            binding.errorView.visibility = View.VISIBLE
            binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
            binding.rvSupportList.visibility = View.GONE
        } else {
            binding.errorView.visibility = View.GONE
            binding.rvSupportList.visibility = View.VISIBLE
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.image_clear -> {
                binding.cetSearch.setText("")
            }
        }
    }

    override fun onClick(view: View, position: Int) {
        val supportedDeviceDetailList = ArrayList<String>()
        supportedDeviceList[position].devices!!.forEach {
            supportedDeviceDetailList.add(it.name!!)
        }
        SupportListActivity.lunch(
            this,
            true,
            Constant.EXTRA_SUPPORTED_DEVICE,
            supportedDeviceDetailList
        )

    }

    fun setUpToolbarTitle(title: String) {

        if (TextUtils.isEmpty(title))
            setToolbarTitle(getString(R.string.support))
        else {
            if (title.equals(Constant.EXTRA_FAQ)) {
                setToolbarTitle(getString(R.string.faqs))
                binding.fakeHint.text = getString(R.string.search_faqs)
            } else {
                setToolbarTitle(getString(R.string.supported_device))
                val isSearchDevice =
                    intent.getBooleanExtra(Constant.SEARCH_DEVICE, false)
                if (isSearchDevice)
                    binding.fakeHint.text = getString(R.string.search_device)
                else binding.fakeHint.text = getString(R.string.search_device_brand)
            }
        }
    }

    override fun isDisplayToolbar(): Boolean {
        return true
    }

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

    private fun animateSearch() {

        var width = binding.layoutSearch.width / 2
        val viewSearchWidth = binding.viewSearch.width / 2
        width = width - viewSearchWidth - SeatelUtils.convertDpToPx(this@SupportListActivity, 10)
        width = -width
        binding.viewSearch.animate().translationX(width.toFloat()).duration = 300
    }

    companion object {
        fun lunch(context: Context, isSearchDevice: Boolean, identify: String, list: List<String>) {
            val intent = Intent(context, SupportListActivity::class.java)
            intent.putExtra(Constant.SUPPORT_IDENTIFY, identify)
            intent.putExtra(Constant.SEARCH_DEVICE, isSearchDevice)
            intent.putStringArrayListExtra(
                Constant.SUPPORTED_DEVICE_DETAIL,
                list as ArrayList<String>
            )
            context.startActivity(intent)
        }
    }


}
