package com.seatel.mobilehall.ui.home.fragment


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintSet
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.FragmentLastFourDigitBinding
import com.seatel.mobilehall.ui.home.interactor.BuyYesSimCardInteractor
import com.seatel.mobilehall.util.AnimationUtil
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.CustomEditText
import com.seatel.mobilehall.util.interactor.KeyBoardNumberInteractor
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.viewFragmentBinding


class LastFourDigitFragment : BaseBuySimFragment(), KeyBoardNumberInteractor, View.OnClickListener,
    BuyYesSimCardInteractor.View {


    private val binding by viewFragmentBinding(
        FragmentLastFourDigitBinding::inflate
    )

    private val mEditTexts = ArrayList<CustomEditText>()
    private lateinit var mSelectEditText: EditText
    private var isClaimFreeSim: Boolean = false
    private var isWinPromotionFreeSim: Boolean = false
    private var simCardPriceFilter: Int = 0

    fun setIsWinPromotionFreeSim(winPromotion: Boolean) {
        this.isWinPromotionFreeSim = winPromotion
    }

    fun setClaimFreeSim(claimFree: Boolean) {
        this.isClaimFreeSim = claimFree
    }

    fun setSimCardPriceFilter(filter: Int) {
        this.simCardPriceFilter = filter
    }

    override fun getIsWinPromotionFreeSim(): Boolean {
        return isWinPromotionFreeSim
    }

    override fun getClaimFreeSim(): Boolean {
        return isClaimFreeSim
    }

    override fun initRecyclerView(): RecyclerView {
        return binding.recyclerViewLastDigit
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return binding.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        //  setFragmentLayout(R.layout.fragment_last_four_digit)
    }

    override fun init() {
        super.init()
        binding.keyboardViewLast.setKeyBoardNumberInteractor(this)
        hideKeyboard(requireActivity())
        if (OrderingManager.getInstance().simPriceDefault == 0.0 || isClaimFreeSim || isWinPromotionFreeSim)
            binding.note.visibility = View.GONE
        if (isClaimFreeSim || isWinPromotionFreeSim) {
            startPrice = simCardPriceFilter
            endPrice = simCardPriceFilter
            binding.itemBuyYesNumber.layoutShowAll.visibility = View.INVISIBLE
        }
        binding.keyboardViewLast.showKeyBoard()

        mEditTexts.add(binding.editTextOne)
        mEditTexts.add(binding.editTextTwo)
        mEditTexts.add(binding.editTextThree)
        mEditTexts.add(binding.editTextFour)
        for (editText in mEditTexts) editText.setOnTouchListener { _, _ -> false }

        mEditTexts[0].requestFocus()
        mSelectEditText = mEditTexts[0]
//        mHiddenTextView = text_view_hidden
        //set size on screen in when small screen size

        val display = requireActivity().windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        val width = size.x
        val height = size.y

        if (width == 480 && height == 800) {
            val constraintSet = ConstraintSet()

            constraintSet.clone(binding.constrainParent)
            constraintSet.setDimensionRatio(binding.editTextOne.id, "0.8")
            constraintSet.setDimensionRatio(binding.editTextTwo.id, "0.8")
            constraintSet.setDimensionRatio(binding.editTextThree.id, "0.8")
            constraintSet.setDimensionRatio(binding.editTextFour.id, "0.8")
//            constraintSet.constrainHeight(binding.editTextOne.id, 30)
//            constraintSet.constrainHeight(binding.editTextTwo.id, 30)
//            constraintSet.constrainHeight(binding.editTextThree.id, 30)
//            constraintSet.constrainHeight(binding.editTextFour.id, 30)
            constraintSet.applyTo(binding.constrainParent)
        }


    }

    //No bottom sheet to show
    override fun initNextBottomSheet() {
    }

    override fun initEvent() {
        super.initEvent()
        binding.buttonSearch.setOnClickListener(this)
        binding.layoutLastFourDigits.setOnClickListener {
            AnimationUtil.instance?.collapse(binding.keyboardViewLast)
        }
        onEditTextClick()
    }

    override fun onClick(v: View?) {
        val ediTextOne = binding.editTextOne.text
        val editTextTwo = binding.editTextTwo.text
        val editTextThree = binding.editTextThree.text
        val editTextFour = binding.editTextFour.text
        var msg = ""
        when {
            ediTextOne!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextTwo!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextThree!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextFour!!.isEmpty() -> msg = getString(R.string.phone_empty)
        }
        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireActivity(), msg).show()
            hideKeyBoard()
        } else {
            AnimationUtil.instance?.collapse(binding.keyboardViewLast)
            lastSelectModel = null
            updateUiAfterItemSelected()
            clearDataNotify()
            searchPhoneNumber()
        }
    }

    private fun onEditTextClick() {
        for (edit in mEditTexts) {
            edit.showSoftInputOnFocus = false
            edit.setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_DOWN) {
                    mSelectEditText = edit
                    edit.setSelection(edit.text!!.length)
                    edit.requestFocus()
                    edit.isCursorVisible = true
                    AnimationUtil.instance?.expand(binding.keyboardViewLast)
                }
                false
            }
        }
    }

    override fun searchPhoneNumber() {
        val search =
            binding.editTextOne.text.toString() + binding.editTextTwo.text.toString() + binding.editTextThree.text.toString() + binding.editTextFour.text.toString()
        buyYesSimCardPresenter?.onSearchPhoneNumber(
            requireContext(),
            search,
            true,
            startPrice,
            endPrice,
            limit(),
            offset
        )
    }

    override fun onKeyBoardKeyClick(key: String) {
        onInsert(key)
    }

    override fun onKeyBoardKeyClearClick() {
        onClear()
    }

    override fun updateUiAfterItemSelected() {
        if (lastSelectModel != null) {
            AnimationUtil.instance?.collapse(binding.keyboardViewLast)
            AnimationUtil.instance?.expand(binding.layoutNext.layoutButtonNext)
//            layout_button_next.visibility = View.VISIBLE
        } else {
            AnimationUtil.instance?.collapse(binding.layoutNext.layoutButtonNext)
//            layout_button_next.visibility = View.GONE
        }
    }

    private fun onInsert(key: String) {
//        if (mHiddenTextView!!.text.length == mEditTexts.size) {
//            return
//        }
//        val pos = getInsertPos(key)
//        val textView = mEditTexts[pos]
//        textView.setText(key)
//        textView.isCursorVisible = false
//        if (pos == mEditTexts.size - 1) {
//            mSelectEditText = mEditTexts[pos]
//            mEditTexts[pos].isCursorVisible = true
//            mEditTexts[pos].requestFocus()
//            return
//        }
//        mSelectEditText = mEditTexts[pos + 1]
//        mEditTexts[pos + 1].requestFocus()
        mSelectEditText.setText(key)
        mSelectEditText.isCursorVisible = false
        mSelectEditText = if (mEditTexts.indexOf(mSelectEditText) == mEditTexts.size - 1) {
            mEditTexts[mEditTexts.size - 1]
        } else {
            mEditTexts[mEditTexts.indexOf(mSelectEditText) + 1]
        }
        mSelectEditText.isCursorVisible = true
        mSelectEditText.setSelection(mSelectEditText.text.length)
        mSelectEditText.requestFocus()
    }

    private fun onClear() {
//        if (mHiddenTextView!!.text.isEmpty()) {
//            mSelectEditText = mEditTexts[0]
//            return
//        }
//        val pos = if (mSelectEditText != null) mEditTexts.indexOf(mSelectEditText) else {
//            getClearPos()
//        }
//        mEditTexts[pos].requestFocus()
//        mEditTexts[pos].isCursorVisible = true
//        mEditTexts[pos].setText("")
//        mSelectEditText = mEditTexts[pos]
        if (mSelectEditText.text.isEmpty()) {
            mSelectEditText.clearFocus()
            mSelectEditText = if (mEditTexts.indexOf(mSelectEditText) == 0) {
                mEditTexts[0]
            } else {
                mEditTexts[mEditTexts.indexOf(mSelectEditText) - 1]
            }
        }
        mSelectEditText.setText("")
        mSelectEditText.isCursorVisible = true
        mSelectEditText.setSelection(mSelectEditText.text.length)
        mSelectEditText.requestFocus()
//        val pos = getClearPos()
//        mEditTexts[pos].requestFocus()
//        mEditTexts[pos].isCursorVisible = true
//        mEditTexts[pos].setText("")
//        mHiddenTextView!!.text = null
//        for (editText in mEditTexts) {
//            editText.text = null
//        }
//        binding.editTextOne.requestFocus()
//        binding.editTextOne.isCursorVisible = true
    }


//    @SuppressLint("SetTextI18n")
//    private fun getInsertPos(key: String): Int {
//        mHiddenTextView!!.text = mHiddenTextView!!.text.toString() + key
//        return mHiddenTextView!!.text.length - 1
//    }
//
//    private fun getClearPos(): Int {
//        mHiddenTextView!!.text = mHiddenTextView!!.text.subSequence(0, mHiddenTextView!!.length() - 1)
//        return mHiddenTextView!!.text.length
//    }


    @SuppressLint("ServiceCast")
    private fun hideKeyboard(activity: Activity) {
        // Check if no view has focus:
        val view = activity.currentFocus
        if (view != null) {
            val inputManager =
                activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    override fun getFragmentOffset(): Int {
        return 100
    }

    override fun isKeyboardHided(): Boolean {
        return binding.keyboardViewLast.visibility == View.GONE
    }

    override fun hideKeyBoard() {
        AnimationUtil.instance?.collapse(binding.keyboardViewLast)
    }

}
