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

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.FragmentFullNumberBinding
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.SeatelUtils
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.viewFragmentBinding

class FullNumberFragment : BaseBuySimFragment(), BuyYesSimCardInteractor.View {

    private val binding by viewFragmentBinding(
        FragmentFullNumberBinding::inflate
    )

    private var isClaimFreeSim: Boolean = false
    private var isWinPromotionFreeSim: Boolean = false
    private var simCardPriceFilter: Int = 0
    private val onTextChange = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            if (TextUtils.isEmpty(binding.fullNameSearch.text.toString())) {
                buyYesSimCardPresenter?.cancelSearchPhoneNumber()
                clearDataNotify()
            }
        }

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

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    }

    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 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_full_number)
        SeatelUtils.hideKeyboard((getmContext() as Activity?)!!)
    }

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

    private fun setKeyBoardData() {
        binding.fullNameSearch.showSoftInputOnFocus = false
        binding.keyboardViewFullNumber.setmMaxLenght(10)
        binding.keyboardViewFullNumber.setmEditText(binding.fullNameSearch)
    }

    // Hide Native Key Board
    fun hideKeyboard(activity: Activity) {
        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 getClaimFreeSim(): Boolean {
        return isClaimFreeSim
    }

    override fun init() {
        super.init()
        binding.fullNameSearch.hint = binding.fullNameSearch.hint
        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
        }
        setKeyBoardData()
    }

    override fun initEvent() {
        super.initEvent()
        binding.fullNameSearch.viewTreeObserver.addOnGlobalLayoutListener(
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    binding.fullNameSearch.requestFocus()
                    binding.fullNameSearch.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            })

        binding.fullNameSearch.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                onEditTextSearchTouch(v)
            }
            false
        }

        binding.buttonSearch.setOnClickListener {
            onButtonSearchClick()
        }

        binding.fullNameSearch.addTextChangedListener(onTextChange)

        binding.viewFragment.setOnClickListener {
            AnimationUtil.instance?.collapse(binding.layoutKeyboard)
            updateUiAfterItemSelected()
        }
    }

    private fun onEditTextSearchTouch(v: View) {
        binding.keyboardViewFullNumber.setmMaxLenght(10)
        binding.keyboardViewFullNumber.showKeyBoard(v as EditText)
        binding.fullNameSearch.requestFocus()
        AnimationUtil.instance?.expand(binding.layoutKeyboard)
        bottomSheetBehavior?.isHideable = true
        bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN
    }

    private fun onButtonSearchClick() {
        val search = binding.fullNameSearch.text
        var msg = ""
        when {
            search!!.isEmpty() || SeatelUtils.isInvalidPhoneFormatSeatelSim(search.toString()) -> msg =
                getString(R.string.please_enter_full_number)
        }
        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireContext(), msg).setCancelable(true).show()
            hideKeyBoard()
        } else {
            clearDataNotify()
            searchPhoneNumber()
        }
    }

    override fun updateUiAfterItemSelected() {
        super.updateUiAfterItemSelected()
        if (lastSelectModel != null) {
            AnimationUtil.instance?.collapse(binding.layoutKeyboard)
        }
    }

    override fun isKeyboardHided(): Boolean {
        return binding.layoutKeyboard.visibility != View.VISIBLE
    }

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

}
