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

import android.Manifest
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import android.widget.EditText
import android.widget.RadioButton
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.android.volley.VolleyError
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.ConfirmationActivity
import com.seatel.mobilehall.ui.invite_friend.InviteFriendScanQrActivity
import com.seatel.mobilehall.ui.login.interactor.VerifyPinInteractor
import com.seatel.mobilehall.ui.login.presenter.VerifyPinPresenter
import com.seatel.mobilehall.util.AnimationUtil
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.FirebaseAnalyticsUtil
import com.seatel.mobilehall.util.PermissionUtil
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.fragment_pin.button_next
import kotlinx.android.synthetic.main.fragment_pin.edit_text_amount
import kotlinx.android.synthetic.main.fragment_pin.edit_text_top_up_phone_number
import kotlinx.android.synthetic.main.fragment_pin.error_view
import kotlinx.android.synthetic.main.fragment_pin.image_scan_barcode
import kotlinx.android.synthetic.main.fragment_pin.keyboard_view_top_up
import kotlinx.android.synthetic.main.fragment_pin.linear_layout_pinless
import kotlinx.android.synthetic.main.fragment_pin.relative_parent_pinless
import kotlinx.android.synthetic.main.fragment_pin.view_amount
import kotlinx.android.synthetic.main.fragment_pin.view_phone_number
import kotlinx.android.synthetic.main.view_radio_button_top_up.radio_button_5_dollar
import kotlinx.android.synthetic.main.view_radio_button_top_up.radio_group_top_up
import org.json.JSONObject

class PinFragment : BaseFragment(), VerifyPinInteractor.View {


    private var mRadioButton: RadioButton? = null
    private lateinit var mView: View
    private var mIsFocus: Boolean = true
    private var mPhone = ""
    private var mPhotoRequest: PermissionUtil.PermissionRequestObject? = null

    //Verify Pin
    private lateinit var mVerifyPinPresenter: VerifyPinPresenter
    private lateinit var mVerifyPinInteractor: VerifyPinInteractor.View

    override fun onVerifyPinNumberSucceed(response: JSONObject) {
        error_view.visibility = View.GONE
        val amount = response.optDouble("amount", 0.0)
        val pin = edit_text_amount.text.toString()
        ConfirmationActivity.lunch(
            getmContext(), edit_text_top_up_phone_number.text.toString(),
            amount, true, pin
        )
    }

    override fun onVerifyPinNumberFailed(error: VolleyError) {
        error_view.visibility = View.GONE
        SeatelAlertDialog.with(getmContext(), SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    fun getViewPhoneNumber(): View {
        return view_phone_number
    }

    fun getViewAmount(): View {
        return view_amount
    }

    fun setPhoneNuber(phone: String) {
        this.mPhone = phone
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_pin)
        FirebaseAnalyticsUtil.getInstance(context).logCustomEvent(Constant.TAB_TOP_UP_PIN)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mView = view
        init()
    }


    private fun showKeyboard() {

        if (!isKeyboardHided()) return
        mView.postDelayed(object : Runnable {
            override fun run() {

                if (mIsFocus) {
                    edit_text_amount.requestFocus()
                    edit_text_amount.isFocusable = true
                    keyboard_view_top_up.showKeyBoard(edit_text_amount)
                } else keyboard_view_top_up.showKeyBoard(edit_text_top_up_phone_number)
                mView.removeCallbacks(this)
            }
        }, 200)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (isVisibleToUser) {
            mView.postDelayed(object : Runnable {
                override fun run() {
                    if (mIsFocus) {
                        edit_text_amount.requestFocus()
                    } else edit_text_top_up_phone_number.requestFocus()
                    mView.removeCallbacks(this)
                }
            }, 200)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        keyboard_view_top_up.hideKeyBoard()
    }

    private fun init() {
        mVerifyPinInteractor = this
        mVerifyPinPresenter = VerifyPinPresenter(getmContext(), this)

        setRadioButtonTextStyle()
        setUpRadioButton()

        edit_text_top_up_phone_number.hint = edit_text_top_up_phone_number.hint
        edit_text_top_up_phone_number.setText(SeatelUtils.phoneNumberFormat(mPhone))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            edit_text_top_up_phone_number.showSoftInputOnFocus = false
            edit_text_amount.showSoftInputOnFocus = false
        }

        edit_text_amount.setSelection(edit_text_amount.text!!.length)
        edit_text_amount.setSelection(0)
        keyboard_view_top_up.setmMaxLenght(30)
        keyboard_view_top_up.showKeyBoard(edit_text_amount)
        edit_text_top_up_phone_number.clearFocus()

        edit_text_top_up_phone_number.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                edit_text_amount.clearFocus()
                edit_text_top_up_phone_number.requestFocus()
                keyboard_view_top_up.setmMaxLenght(15)
                keyboard_view_top_up.showKeyBoard(v as EditText)
                AnimationUtil.instance?.collapse(radio_group_top_up)
                linear_layout_pinless.animate().translationY(0f).duration = 300
                mIsFocus = false
            }
            false
        }

        edit_text_amount.viewTreeObserver.addOnGlobalLayoutListener(
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    edit_text_amount.requestFocus()
                    edit_text_amount.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            })
        edit_text_amount.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                keyboard_view_top_up.setmMaxLenght(30)
                keyboard_view_top_up.showKeyBoard(v as EditText)
                edit_text_amount.requestFocus()
                edit_text_top_up_phone_number.clearFocus()
                mIsFocus = true

            }
            false
        }
        edit_text_top_up_phone_number.isFocusable = true
        relative_parent_pinless.setOnClickListener { hideKeyBoard() }


        image_scan_barcode.setOnClickListener {
            val options = ScanOptions()
            options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES)
            //options.setPrompt("Scan a barcode")
            options.setCameraId(0) // Use a specific camera of the device
            options.setBeepEnabled(false)
            options.setOrientationLocked(false)
            options.setBarcodeImageEnabled(true)
            barcodeLauncher.launch(options)
        }


    }

    // Register the launcher and result handler
    private val barcodeLauncher = registerForActivityResult(
        ScanContract()
    ) { result: ScanIntentResult ->
        if (result.contents == null) {
            // Toast.makeText(requireContext(), "Cancelled", Toast.LENGTH_LONG).show()
        } else {
            val mResult = result.contents.substringBeforeLast("*")
            val finalResult = mResult.substringAfterLast("*")
            edit_text_amount.setText(finalResult)
        }
    }

    private fun validateControl(): Boolean {
        val amount = edit_text_amount.text.toString().trim()
        var phone = edit_text_top_up_phone_number.text?.trim().toString()
        phone = phone.replace(" ", "")

        var strMessage = ""

        if (TextUtils.isEmpty(phone)) {
            strMessage = getString(R.string.phone_empty)

        } else if (phone.startsWith("0") && phone.length < 9 ||
            phone.startsWith("85") && phone.length < 11 || phone.length < 8
        )
            strMessage = getString(R.string.incorrect_phone_num)
        else if (TextUtils.isEmpty(amount))
            strMessage = getString(R.string.topup_pin_empty)

        if (!TextUtils.isEmpty(strMessage)) {
            SeatelAlertDialog.with(getmContext(), strMessage).show()
            return false
        }


        return true
    }

    private fun startVerifyPin() {
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        val pin = edit_text_amount.text.toString()
        mVerifyPinPresenter.onVerifyPinNumber(pin)
    }

    private fun setUpRadioButton() {

        mRadioButton = radio_button_5_dollar
        radio_group_top_up.setOnCheckedChangeListener { radioGroup, _ ->

            if (mRadioButton != null) {
                mRadioButton!!.setTextColor(
                    ContextCompat.getColor(
                        getmContext(),
                        R.color.colorBlue
                    )
                )
                mRadioButton!!.textSize = 16f
            }

            val radioButtonId: Int = radioGroup.checkedRadioButtonId

            val radioButton = radioGroup.findViewById<RadioButton>(radioButtonId) as RadioButton
            radioButton.setTextColor(ContextCompat.getColor(getmContext(), android.R.color.white))

            radioButton.textSize = 18f
            edit_text_amount.setText(radioButton.tag.toString())

            mRadioButton = radioButton
            edit_text_amount.setSelection(edit_text_amount.text!!.length)
        }
        button_next.setOnClickListener {
            hideKeyBoard()
            if (validateControl()) {
                startVerifyPin()
            }
        }
    }

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

    override fun hideKeyBoard() {
        super.hideKeyBoard()
        keyboard_view_top_up.hideKeyBoard()
    }

    private fun setRadioButtonTextStyle() {

        val topUp = resources.getStringArray(R.array.top_up_amount)
        for (i in 0 until radio_group_top_up.childCount) {
            (radio_group_top_up.getChildAt(i) as RadioButton).text = SeatelUtils.fromHtml(topUp[i])
        }
    }

    private fun showPermissionCamera() {
        mPhotoRequest = PermissionUtil.with(this).request(Manifest.permission.CAMERA)
            .onAllGranted(object : PermissionUtil.Func() {
                override fun call() {
                    InviteFriendScanQrActivity.launchForResult(
                        requireContext()
                    )
                }

            }).onAnyDenied(object : PermissionUtil.Func() {
                override fun call() {
                    Toast.makeText(
                        requireContext(),
                        "Camera permission is needed to open camera.",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }).askPermission(999)
    }
}