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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.NoConnectionError
import com.android.volley.TimeoutError
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ActivityMyOrderBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.AdapterListParentOrder
import com.seatel.mobilehall.ui.home.interactor.MyOrderInteractor
import com.seatel.mobilehall.ui.home.interactor.UpdatedMyOrderProcessInteractor
import com.seatel.mobilehall.ui.home.model.MyOrderListModel
import com.seatel.mobilehall.ui.home.presenter.MyOrderPresenter
import com.seatel.mobilehall.ui.home.presenter.UpdatedMyOrderProcessPresenter
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import org.json.JSONObject

class MyOrderActivity : BaseActivity<ActivityMyOrderBinding>(), View.OnClickListener,
    MyOrderInteractor.View,
    UpdatedMyOrderProcessInteractor.View {

    private var mMyOrderPresenter: MyOrderPresenter? = null
    private var mMyOrderAdapter: AdapterListParentOrder? = null
    private var mView: MyOrderInteractor.View? = null
    private var mPostOrder: UpdatedMyOrderProcessPresenter? = null
    private var linearLayoutManager: LinearLayoutManager? = null
    private var mOffset = 0
    private val mLimit = 10
    private var marginLayoutParams: ViewGroup.MarginLayoutParams? = null
    private var flagMove = 1
    private var lastSearchStr = ""

    override fun onClick(v: View?) {
        if (v != null) {
            when (v.id) {
                R.id.recycler_eshop_phase_two, R.id.error_view -> {
                    binding.textViewSearchOrder.clearFocus()
                    SeatelUtils.hideKeyboard(this@MyOrderActivity)
                }

                else -> HistoryActivity.lunch(applicationContext)
            }
        }

    }

    override fun onDeletedOrderId(orderId: String) {
    }

    override fun onClickConfirmOrder(orderId: String) {
        SeatelAlertDialog.with(this, getString(R.string.you_have_recieved_this_order))
            .setCancelable(true).setPositiveButton("Yes") { dialog, _ ->
                binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
                mPostOrder?.onPutOrderProcess(orderId)
                dialog.dismiss()
            }.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }.show()
    }

    override fun responseMyOrderSucceed(myOrderList: ArrayList<MyOrderListModel>) {
        if (myOrderList.isEmpty() && mOffset == 0) {
            animateSearchBoxHideShow(true)
            binding.errorView.errorMessage = getString(R.string.no_myorder)
            binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
        } else {
            mMyOrderAdapter?.addItems(myOrderList)
            binding.errorView.visibility = View.GONE
            binding.textViewSearchOrder.visibility = View.VISIBLE
        }
    }

    override fun onLoadMore() {
        if (mMyOrderAdapter?.getSizeItems() == 0) return
        mOffset += mLimit
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun responseMyOrderFail(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 -> {
                animateSearchBoxHideShow(true)
                binding.errorView.errorMessage = getString(R.string.no_myorder)
                binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)

            }
        }
    }

    private fun getMyOrderList() {
        binding.textViewSearchOrder.clearFocus()
        SeatelUtils.hideKeyboard(this)
        mMyOrderAdapter?.clearData()
        mOffset = 0
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter?.onGetMyOrderData(mOffset)
    }

    override fun onPostOrderProcessSucceed(response: JSONObject) {
        SeatelAlertDialog.with(this, getString(R.string.thank_you_for_purchase)).show()
        getMyOrderList()
    }

    override fun onPostOrderProcessTokenFailed(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 -> {
                if (mOffset == 0) {
                    binding.errorView.errorMessage = getString(R.string.no_myorder)
                    binding.errorView.setViewMode(ErrorHandleView.Mode.NO_DATA)
                } else {
                    binding.errorView.visibility = View.GONE
                }
            }
        }
    }

    private fun animateSearchBoxHideShow(isShow: Boolean) {
        if (isShow) {
            if (flagMove == 1) return
            flagMove = 1
            binding.textViewSearchOrder.animate().translationY(0f).withEndAction {
                marginLayoutParams?.bottomMargin = 0
                binding.recyclerViewOrderParent.layoutParams = marginLayoutParams
            }.duration = 400
            binding.recyclerViewOrderParent.animate().translationY(0f).duration = 400

        } else {
            if (flagMove == 0) return
            flagMove = 0
            binding.textViewSearchOrder.animate().translationY(-140f).duration = 400
            binding.recyclerViewOrderParent.animate().translationY(-140f).duration = 400
            marginLayoutParams?.bottomMargin = -140
            binding.recyclerViewOrderParent.layoutParams = marginLayoutParams
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterUpAnimation()
      //  setContentView(R.layout.activity_my_order)
        binding.textViewSearchOrder.hint = binding.textViewSearchOrder.hint

        mView = this
        mPostOrder = UpdatedMyOrderProcessPresenter(this, this)

        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mMyOrderPresenter = MyOrderPresenter(this)
        mMyOrderPresenter?.setPhoneNumber(getPhoneLogin())
        getMyOrderList()

        mMyOrderAdapter = mView?.let { AdapterListParentOrder(this, ArrayList(), false, it) }
        binding.recyclerViewOrderParent.adapter = mMyOrderAdapter
        linearLayoutManager = LinearLayoutManager(this)
        binding.recyclerViewOrderParent.layoutManager = linearLayoutManager

        marginLayoutParams =
            binding.recyclerViewOrderParent.layoutParams as ViewGroup.MarginLayoutParams

        binding.recyclerViewOrderParent.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mMyOrderAdapter?.onScrollEvent(linearLayoutManager!!)
                if (dy > 0)
                    animateSearchBoxHideShow(false)
                else animateSearchBoxHideShow(true)
            }
        })

        binding.textViewBottomEshop.text = getString(R.string.history)
        binding.layoutCallViewMyOrder.setOnClickListener(this)

        binding.recyclerViewOrderParent.setOnClickListener(this)
//        binding.errorView.setOnClickListener(this)

        binding.textViewSearchOrder.setImeActionLabel("Search", EditorInfo.IME_ACTION_SEARCH)
        binding.textViewSearchOrder.setOnEditorActionListener { _, actionId, _ ->
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE -> {
                    if (!TextUtils.isEmpty(binding.textViewSearchOrder.text.toString())) {
                        lastSearchStr = binding.textViewSearchOrder.text.toString()
                        mMyOrderPresenter?.setsearchStr(lastSearchStr)
                        getMyOrderList()
                        return@setOnEditorActionListener true
                    } else if (TextUtils.isEmpty(binding.textViewSearchOrder.text.toString()) && lastSearchStr.isNotEmpty()) {
                        mMyOrderPresenter?.setsearchStr("")
                        getMyOrderList()
                    } else {
                        binding.textViewSearchOrder.clearFocus()
                        SeatelUtils.hideKeyboard(this)
                    }
                }
            }
            return@setOnEditorActionListener false
        }

    }

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

    override fun getStringToolbarTitle(): String? {
        return getString(R.string.my_order)
    }

    override fun isDisplayHome(): Boolean {
        return true
    }

    override fun isShowBackButtonLeft(): Boolean {
        return true
    }

    override fun isCancelBackType(): Boolean {
        return true
    }

    companion object {
        fun lunch(context: Context) {
            val intent = Intent(context, MyOrderActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

}
