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

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import com.android.volley.Request
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.prefs.ProfileSharedPreference
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.FragmentOrderPickUpBinding
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.YesHubNearestActivity
import com.seatel.mobilehall.ui.home.model.SeatelShopLocationModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.BottomChooserDialog
import com.seatel.mobilehall.util.manager.OrderProfileSingleton
import com.seatel.mobilehall.util.manager.OrderingManager
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.regex.Matcher
import java.util.regex.Pattern

class OrderPickUpDeliveryFragment : BaseFragment(), OrderingManager.OrderCallback,
    View.OnClickListener, TextWatcher {

    private var shopName: String = ""
    private var shopId: String = ""
    private var tempShopId: String = ""
    private var phoneNumber: String = ""
    private var address: String = OrderingManager.getInstance().addressSave
    private var firstNameDelivery: String = OrderingManager.getInstance().firstNameSave
    private var lastNameDelivery: String = OrderingManager.getInstance().lastNameSave
    private var emailDelivery: String = OrderingManager.getInstance().emailSave
    private var phoneNumberDelivery: String = OrderingManager.getInstance().phoneNumberSave
    private var province: String = OrderingManager.getInstance().provinceSave
    private var strTempAddrss: String = OrderingManager.getInstance().addressSave
    private val provinceModel = ArrayList<BottomChooserDialog.BottomChooserModel>()
    private var postDelay: Handler? = null

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_title_pickup, R.id.image_view_edit, R.id.radio_pick -> {
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.DELIVERY && checkIsInfoAddressUpdated()) {
                    setDataInputDeliveryDefault()
                }
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.PICKUP && v.id != R.id.image_view_edit && binding.ctvEditPickup.visibility == View.GONE) {
                    return
                }

                if (binding.ctvEditPickup.visibility == View.GONE && binding.ctvSavePickup.visibility == View.GONE) OrderingManager.getInstance().deliverStatus =
                    null
                OrderingManager.getInstance().isSelectedDelivery = false
                updateLayoutService(OrderingManager.DeliverStatus.PICKUP)
                binding.radioDelivery.isChecked = false
                binding.radioPick.isChecked = true
                if (binding.radioPick.isChecked) {
                    if (postDelay == null) postDelay = Handler()
                    if (postDelay != null) postDelay?.postDelayed({
                        setDataPickupInfoInput()
                        if (binding.ctvEditPickup.visibility == View.GONE && binding.ctvSavePickup.visibility == View.GONE) binding.radioPick.isChecked =
                            false
                        postDelay?.removeCallbacksAndMessages(this)
                        postDelay = null
                    }, 200)
                }
            }

            R.id.view_title_delivery, R.id.radio_delivery -> {
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.PICKUP && checkIsInfoAddressUpdated()) {
                    setDataPickupInfoInput()
                }
                if ((OrderingManager.getInstance().claimFreeSim || OrderingManager.getInstance().winPromotionFreeSim) && checkIsDeliveryClaimFreeSim()) {
                    binding.radioDelivery.isChecked = false
                    return
                }
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.DELIVERY && binding.ctvEditDelivery.visibility == View.GONE) {
                    return
                }
                OrderingManager.getInstance().isSelectedDelivery = true
                binding.radioDelivery.isChecked = false
                updateLayoutService(OrderingManager.DeliverStatus.DELIVERY)
                binding.radioPick.isChecked = false
                binding.viewEditPickup.visibility = View.GONE

            }

            R.id.ctv_edit_delivery -> {
                showDeliveryInput()
                checkIsInfoAddressUpdated()
            }

            R.id.ctv_done_save -> {
                if (checkValidateFieldInput()) return
                if (checkIsInfoAddressUpdated()) {
                    firstNameDelivery = binding.editTextFirstName.text.toString()
                    lastNameDelivery = binding.editTextLastName.text.toString()
                    emailDelivery = binding.editTextEmail.text.toString()
                    phoneNumberDelivery = binding.editTextPhoneNumber.text.toString()
                    address = binding.editTextAddress.text.toString()
                    province = binding.editTextProvince.text.toString()
                    putDeliveryInfo()
                }

                showDeliveryLocation(address, province)
                SeatelUtils.hideKeyboard(getmContext() as Activity)
            }

            R.id.ctv_done_cancel -> {
                if (checkIsEmptyAll()) {
                    OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
                    OrderingManager.getInstance().deliverStatus = null
                    binding.layoutDeliveryLocation.visibility = View.GONE
                    binding.ctvDoneSave.visibility = View.GONE
                    binding.ctvDoneCancel.visibility = View.GONE
                    binding.ctvEditDelivery.visibility = View.GONE
                    binding.viewInputPickup.visibility = View.GONE
                    binding.radioDelivery.isChecked = false
                    OrderingManager.getInstance().isSelectedDelivery = false
                    binding.layoutDelivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
                } else {
                    showDeliveryLocation(address, province)
                    SeatelUtils.hideKeyboard(getmContext() as Activity)
                }
                setDataInputDeliveryDefault()
                checkIsInfoAddressUpdated()
            }

            R.id.edit_text_province -> {
                showProvinceBottomDialog()
            }

            R.id.ctv_edit_pickup -> {
                checkIsInfoAddressUpdated()
                setDataPickupInfoInput()
                binding.ctvEditPickup.visibility = View.GONE
                binding.ctvCancelPickup.visibility = View.VISIBLE
                binding.ctvSavePickup.visibility = View.VISIBLE
                binding.viewShowPickup.visibility = View.GONE
                binding.viewInputPickup.visibility = View.VISIBLE
            }

            R.id.ctv_save_pickup -> {
                if (checkValidateFieldInputPickUp()) return
                if (checkIsInfoAddressUpdated()) {
                    firstNameDelivery = binding.editTextFirstNamePickup.text.toString()
                    lastNameDelivery = binding.editTextLastNamePickup.text.toString()
                    emailDelivery = binding.editTextEmailPickup.text.toString()
                    phoneNumberDelivery = binding.editTextPhoneNumberPickup.text.toString()
                    putDeliveryInfo(true)
                } else showInputPickup()
                SeatelUtils.hideKeyboard(getmContext() as Activity)
                OrderingManager.getInstance().updatedPickupAddress = false
            }

            R.id.ctv_cancel_pickup -> {
                if (checkIsEmptyAll(true)) {
                    OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
                    OrderingManager.getInstance().deliverStatus = null
                    binding.layoutPickLocation.visibility = View.GONE
                    binding.ctvSavePickup.visibility = View.GONE
                    binding.ctvCancelPickup.visibility = View.GONE
                    binding.ctvEditPickup.visibility = View.GONE
                    binding.imageViewEdit.visibility = View.GONE
                    binding.radioPick.isChecked = false
                    binding.tvPickDes.visibility = View.GONE
                    binding.viewShowPickup.visibility = View.GONE
                    binding.viewInputPickup.visibility = View.GONE
                    OrderingManager.getInstance().isSelectedDelivery = false
                    binding.layoutPickUp.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
                } else {
                    showInputPickup()
                    setDataPickupInfoInput()
                    checkIsInfoAddressUpdated()
                }
                SeatelUtils.hideKeyboard(getmContext() as Activity)
            }
        }
    }

    private fun checkIsEmptyAll(isPickup: Boolean = false): Boolean {
        if (isPickup) return firstNameDelivery.isEmpty() || lastNameDelivery.isEmpty() || emailDelivery.isEmpty() || phoneNumberDelivery.isEmpty()
        return address.isEmpty() || province.isEmpty() || firstNameDelivery.isEmpty() || lastNameDelivery.isEmpty() || emailDelivery.isEmpty() || phoneNumberDelivery.isEmpty()
    }

    fun checkIsInfoAddressUpdated(): Boolean {
        var check = false
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
            when {
                !TextUtils.equals(
                    binding.editTextFirstName.text.toString(), firstNameDelivery
                ) || TextUtils.equals(binding.editTextFirstName.text.toString(), "") -> check = true

                !TextUtils.equals(
                    binding.editTextLastName.text.toString(), lastNameDelivery
                ) || TextUtils.equals(binding.editTextLastName.text.toString(), "") -> check = true

                !TextUtils.equals(
                    binding.editTextEmail.text.toString(), emailDelivery
                ) || TextUtils.equals(binding.editTextEmail.text.toString(), "") -> check = true

                !TextUtils.equals(
                    binding.editTextPhoneNumber.text.toString(), phoneNumberDelivery
                ) || TextUtils.equals(binding.editTextPhoneNumber.text.toString(), "") -> check =
                    true

                !TextUtils.equals(
                    binding.editTextAddress.text.toString(),
                    address
                ) || TextUtils.equals(
                    binding.editTextAddress.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    binding.editTextProvince.text.toString(),
                    SeatelUtils.translatForDialog(context, province)
                ) || TextUtils.equals(binding.editTextProvince.text.toString(), "") -> check = true
            }
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            when {
                !TextUtils.equals(
                    binding.editTextFirstNamePickup.text.toString(), firstNameDelivery
                ) || TextUtils.equals(
                    binding.editTextFirstNamePickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    binding.editTextLastNamePickup.text.toString(), lastNameDelivery
                ) || TextUtils.equals(
                    binding.editTextLastNamePickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    binding.editTextEmailPickup.text.toString(), emailDelivery
                ) || TextUtils.equals(binding.editTextEmailPickup.text.toString(), "") -> check =
                    true

                !TextUtils.equals(
                    binding.editTextPhoneNumberPickup.text.toString(), phoneNumberDelivery
                ) || TextUtils.equals(
                    binding.editTextPhoneNumberPickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(shopId, tempShopId) || TextUtils.equals(tempShopId, "") -> check =
                    true
            }
        }
        OrderingManager.getInstance().updatedPickupAddress = check
        OrderingManager.getInstance().updatedDeliveryAddress = check


        return check
    }


    private fun setDataPickupInfoInput() {
        binding.editTextFirstNamePickup.setText(firstNameDelivery)
        binding.editTextLastNamePickup.setText(lastNameDelivery)
        binding.editTextEmailPickup.setText(emailDelivery)
        binding.editTextPhoneNumberPickup.setText(phoneNumberDelivery)
    }

    private fun setDataDeliveryDisplayInfo() {
        binding.ctvAddressDelivery.text = address
        binding.ctvCityDelivery.text = province
        binding.ctvFirstNameDelivery.text = firstNameDelivery
        binding.ctvLastNameDelivery.text = lastNameDelivery
        binding.ctvEmailDelivery.text = emailDelivery
        binding.ctvPhoneNumberDelivery.text = phoneNumberDelivery
    }

    private fun setDataPickupDisplayInfo() {
        binding.ctvFirstNamePickup.text = firstNameDelivery
        binding.ctvLastNamePickup.text = lastNameDelivery
        binding.ctvEmailPickup.text = emailDelivery
        binding.ctvPhoneNumberPickup.text = phoneNumberDelivery
    }

    private fun showInputPickup() {
        binding.viewEditPickup.visibility = View.VISIBLE
        if (checkIsEmptyAll(true)) {
            binding.ctvEditPickup.visibility = View.GONE
            binding.ctvCancelPickup.visibility = View.VISIBLE
            binding.ctvSavePickup.visibility = View.VISIBLE
            binding.viewShowPickup.visibility = View.GONE
            binding.viewInputPickup.visibility = View.VISIBLE
        } else {
            binding.ctvSavePickup.visibility = View.GONE
            binding.ctvCancelPickup.visibility = View.GONE
            binding.ctvEditPickup.visibility = View.VISIBLE
            binding.viewShowPickup.visibility = View.VISIBLE
            binding.viewInputPickup.visibility = View.GONE
            SeatelUtils.hideKeyboard(getmContext() as Activity)
        }
    }

    private fun visiblePickupAddress() {
        binding.viewEditPickup.visibility = View.VISIBLE
        binding.ctvSavePickup.visibility = View.GONE
        binding.ctvCancelPickup.visibility = View.GONE
        binding.ctvEditPickup.visibility = View.VISIBLE
        binding.viewShowPickup.visibility = View.VISIBLE
        binding.viewInputPickup.visibility = View.GONE
        SeatelUtils.hideKeyboard(getmContext() as Activity)
        checkIsInfoAddressUpdated()
    }

    private fun checkIsDeliveryClaimFreeSim(): Boolean {
        if (OrderingManager.getInstance().topupAmountClaimFreeSim == 0.0) {
            SeatelAlertDialog.with(
                getmContext(), "To select delivery, you need to top up at least $1."
            ).show()
            return true
        }
        return false
    }

    private fun checkValidateFieldInputPickUp(): Boolean {
        var str = ""
        val ps: Pattern = Pattern.compile("^[a-zA-Z]+$")
        //First Name
        val firstName: Matcher = ps.matcher(binding.editTextFirstNamePickup.text.toString().trim())
        val bs: Boolean = firstName.matches()
        if (!bs) {
            str = getString(R.string.please_enter_valid_first_name)
            binding.editTextFirstName.requestFocus()
        }

        //Last Name
        val lastName: Matcher = ps.matcher(binding.editTextLastNamePickup.text.toString().trim())
        val bsLastName: Boolean = lastName.matches()
        if (!bsLastName) {
            binding.editTextLastName.requestFocus()
            str = getString(R.string.please_enter_valid_last_name)
        }
        when {
            TextUtils.isEmpty(binding.editTextFirstNamePickup.text.toString().trim()) -> {
                str = getString(R.string.please_enter_delivery_first_name)
                binding.editTextFirstNamePickup.requestFocus()
            }

            TextUtils.isEmpty(binding.editTextLastNamePickup.text.toString().trim()) -> {
                binding.editTextLastNamePickup.requestFocus()
                str = getString(R.string.please_enter_delivery_last_name)
            }

            TextUtils.isEmpty(binding.editTextEmailPickup.text.toString().trim()) -> {
                binding.editTextEmailPickup.requestFocus()
                str = getString(R.string.please_enter_delivery_email)
            }

            SeatelUtils.isEmailValid(binding.editTextEmailPickup.text.toString().trim()) -> {
                binding.editTextEmailPickup.requestFocus()
                str = getString(R.string.email_invalid)
            }

            TextUtils.isEmpty(binding.editTextPhoneNumberPickup.text.toString().trim()) -> {
                binding.editTextPhoneNumberPickup.requestFocus()
                str = getString(R.string.please_enter_delivery_phone_number)
            }

            !SeatelUtils.isValidatePhoneFormat(
                binding.editTextPhoneNumberPickup.text.toString().trim()
            ) -> {
                binding.editTextPhoneNumberPickup.requestFocus()
                str = getString(R.string.valid_phone_number)
            }
        }
        if (str.isNotEmpty()) {
            SeatelAlertDialog.with(requireContext(), str).show()
            return true
        }
        return false
    }

    private fun checkValidateFieldInput(): Boolean {
        var str = ""
        val ps: Pattern = Pattern.compile("^[a-zA-Z]+$")
        //First Name
        val firstName: Matcher = ps.matcher(binding.editTextFirstName.text.toString().trim())
        val bs: Boolean = firstName.matches()
        if (!bs) {
            str = getString(R.string.please_enter_valid_first_name)
            binding.editTextFirstName.requestFocus()
        }
        //Last Name
        val lastName: Matcher = ps.matcher(binding.editTextLastName.text.toString().trim())
        val bsLastName: Boolean = lastName.matches()
        if (!bsLastName) {
            binding.editTextLastName.requestFocus()
            str = getString(R.string.please_enter_valid_last_name)
        }
        when {
            TextUtils.isEmpty(binding.editTextFirstName.text.toString().trim()) -> {
                str = getString(R.string.please_enter_delivery_first_name)
                binding.editTextFirstName.requestFocus()
            }

            TextUtils.isEmpty(binding.editTextLastName.text.toString().trim()) -> {
                binding.editTextLastName.requestFocus()
                str = getString(R.string.please_enter_delivery_last_name)
            }

            TextUtils.isEmpty(binding.editTextEmail.text.toString().trim()) -> {
                binding.editTextEmail.requestFocus()
                str = getString(R.string.please_enter_delivery_email)
            }

            SeatelUtils.isEmailValid(binding.editTextEmail.text.toString().trim()) -> {
                binding.editTextEmail.requestFocus()
                str = getString(R.string.email_invalid)
            }

            TextUtils.isEmpty(binding.editTextPhoneNumber.text.toString().trim()) -> {
                binding.editTextPhoneNumber.requestFocus()
                str = getString(R.string.please_enter_delivery_phone_number)
            }

            !SeatelUtils.isValidatePhoneFormat(
                binding.editTextPhoneNumber.text.toString().trim()
            ) -> {
                binding.editTextPhoneNumber.requestFocus()
                str = getString(R.string.valid_phone_number)
            }

            TextUtils.isEmpty(binding.editTextAddress.text.toString().trim()) -> {
                binding.editTextAddress.requestFocus()
                str = getString(R.string.please_enter_delivery)
            }

            TextUtils.isEmpty(binding.editTextProvince.text.toString()) -> str =
                getString(R.string.please_select_delivery_province)
        }
        if (str.isNotEmpty()) {
            SeatelAlertDialog.with(requireContext(), str).show()
            return true
        }
        return false
    }


    fun isValidData(): Boolean {
        if (TextUtils.isEmpty(
                binding.activateSimView.getTvIdType()
            ) || TextUtils.isEmpty(binding.activateSimView.getCertificationNamePost())
        ) {
            SeatelAlertDialog.with(requireContext(), "Please select Document Type.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.getEditTextName())) {
            SeatelAlertDialog.with(requireContext(), "Please input your name.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.getEditTextCardNumber())) {
            SeatelAlertDialog.with(requireContext(), "Please input your ID number.").show()
            return false
        }

        if (TextUtils.isEmpty(binding.activateSimView.getTvSex())) {
            SeatelAlertDialog.with(requireContext(), "Please select your gender.").show()
            return false
        }

        if (TextUtils.isEmpty(binding.activateSimView.getTvDate()) || (TextUtils.isEmpty(
                binding.activateSimView.getTvMonth()
            )) || (TextUtils.isEmpty(binding.activateSimView.getTvYear()))
        ) {
            SeatelAlertDialog.with(requireContext(), "Please select your date of birth.").show()
            return false
        }

        if (binding.activateSimView.mOutputFront.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID front.").show()
            return false
        }

        if (binding.activateSimView.mOutputBack.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID back.").show()
            return false
        }

        if (binding.activateSimView.mOutputUser.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take your photo.").show()
            return false
        }

        /*if (binding.activateSimView.mOutputFileFront == null) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID front.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileBack == null) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID back.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileUser == null) {
            SeatelAlertDialog.with(requireContext(), "Please take your photo.").show()
            return false
        }*/
        return true
    }

    fun showValidateFieldOnNextClick() {
        when (OrderingManager.getInstance().deliverStatus) {
            OrderingManager.DeliverStatus.DELIVERY -> checkValidateFieldInput()
            OrderingManager.DeliverStatus.PICKUP -> checkValidateFieldInputPickUp()
        }

    }

    fun setPhoneNumber(phone: String) {
        this.phoneNumber = phone
    }

    override fun onCartModify() {
    }

    override fun onCartModifyQty() {
    }

    override fun onDeliveryData(seatelShopLocationModel: SeatelShopLocationModel?) {
        if (seatelShopLocationModel != null) updateData(seatelShopLocationModel)
    }

    private var tmpDeliveryStatus: OrderingManager.DeliverStatus? = null

    private var _binding: FragmentOrderPickUpBinding? = null
    private val binding get() = _binding!!

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

    private fun showProvinceBottomDialog() {
        if (provinceModel.size > 0) {
            BottomChooserDialog(requireContext()).addItems(
                provinceModel,
                object : BottomChooserDialog.OnItemChooser {
                    override fun onChose(
                        position: Int, data: BottomChooserDialog.BottomChooserModel
                    ) {

                        OrderingManager.getInstance().updatedDeliveryAddress =
                            !TextUtils.equals(data.name, binding.editTextProvince.text.toString())
                        binding.editTextProvince.text = data.name
                    }
                }).show()
        }
    }

    private fun getProvinceData() {
        object : SeatelJSONArrayRequest(context) {
            override fun getFunctionName(): String {
                return "province?lang=$languageCode"
            }
        }.execute {
            val provinceJson = it as JSONArray
            val provinceSet = hashSetOf<String>()
            for (i in 0 until provinceJson.length()) {
                provinceSet.add(provinceJson.optJSONObject(i).optString("title"))
                provinceModel.add(
                    BottomChooserDialog.BottomChooserModel(
                        0, provinceJson.optJSONObject(i).optString("title")
                    )
                )
            }
            SeatelSharePreferences.getInstance(requireContext())?.setProvinceData(provinceSet)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        _binding = FragmentOrderPickUpBinding.bind(view)

        binding.activateSimView.displayForOrderPickUp()
        Log.d("TAG", "onViewCreated: ${binding.activateSimView.mOutputFront}")

        if ((OrderingManager.getInstance().claimFreeSim)) binding.viewNoteClaimFreeSim.visibility =
            View.VISIBLE
        if (OrderingManager.getInstance().winPromotionFreeSim) binding.layoutDelivery.visibility =
            View.GONE

        if (OrderingManager.getInstance().buyTopUpCard) binding.layoutProfileId.visibility =
            View.GONE

        binding.titleAddress.text = binding.titleAddress.text.toString() + ":"
        binding.editTextAddress.hint =
            SeatelUtils.translatForDialog(context, "Address (Ex: House #, Street 22, Chamkamon)")
        binding.editTextProvince.hint =
            SeatelUtils.translatForDialog(context, "City/Province (Ex: Phnom Penh)")

        val provinceData = SeatelSharePreferences.getInstance(requireContext())?.getProvinceData()
        if (provinceData != null) {
            for (i in provinceData.indices) {
                provinceModel.add(
                    BottomChooserDialog.BottomChooserModel(
                        0, provinceData.elementAt(i)!!
                    )
                )
            }
        } else {
            getProvinceData()
        }

        binding.ctvEditPickup.setOnClickListener(this)
        binding.ctvSavePickup.setOnClickListener(this)
        binding.ctvCancelPickup.setOnClickListener(this)

        binding.viewTitlePickup.setOnClickListener(this)
        binding.radioPick.setOnClickListener(this)
        binding.radioDelivery.setOnClickListener(this)
        binding.viewTitleDelivery.setOnClickListener(this)
        OrderingManager.getInstance().orderCallback = this
        if (OrderingManager.getInstance().locationModel != null) {
            tmpDeliveryStatus = OrderingManager.getInstance().deliverStatus
            updateData(OrderingManager.getInstance().locationModel, true)
        }
        binding.editTextProvince.setOnClickListener(this)
        binding.ctvDoneSave.setOnClickListener(this)
        binding.ctvDoneCancel.setOnClickListener(this)
        if (OrderingManager.getInstance().locationModel == null) getDeliveryInfo()
        else {
            address = OrderingManager.getInstance().addressSave
            province = OrderingManager.getInstance().provinceSave
            firstNameDelivery = OrderingManager.getInstance().firstNameSave
            lastNameDelivery = OrderingManager.getInstance().lastNameSave
            emailDelivery = OrderingManager.getInstance().emailSave
            phoneNumberDelivery = OrderingManager.getInstance().phoneNumberSave
            setDataPickupInfoInput()
            setDataDeliveryDisplayInfo()
            setDataInputDeliveryDefault()
            checkIsInfoAddressUpdated()
        }
        binding.editTextFirstName.addTextChangedListener(this)
        binding.editTextLastName.addTextChangedListener(this)
        binding.editTextEmail.addTextChangedListener(this)
        binding.editTextPhoneNumber.addTextChangedListener(this)
        binding.editTextAddress.addTextChangedListener(this)

        binding.editTextFirstNamePickup.addTextChangedListener(this)
        binding.editTextLastNamePickup.addTextChangedListener(this)
        binding.editTextEmailPickup.addTextChangedListener(this)
        binding.editTextPhoneNumberPickup.addTextChangedListener(this)

        //  getProfileData()
        Log.d(
            "profile:>>>", "onViewCreated: ${
                ProfileSharedPreference.getInstance(requireContext())?.getDocumentType()
            } ${ProfileSharedPreference.getInstance(requireContext())?.getName()}"
        )
    }

    private fun getProfileData() {

        val orderProfile = OrderProfileSingleton.getInstance(requireContext())

        binding.activateSimView.getmTvIdType().addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setDocType(binding.activateSimView.getCertificationNamePost()!!)
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })

        binding.activateSimView.getmEditTextCardNumber()
            .addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                    orderProfile?.setNationalityId(binding.activateSimView.getEditTextCardNumber())
                }

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

                }

                override fun afterTextChanged(s: Editable?) {

                }

            })
        binding.activateSimView.getmEditTextName().addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setName(binding.activateSimView.getEditTextName())
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        binding.activateSimView.getmTvSex().addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setGender(binding.activateSimView.getGenderKeyPost())
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        binding.activateSimView.getmTvDate().addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setDateOfBirth(binding.activateSimView.dateOfBirth)
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })


        binding.activateSimView.setTvIdType(orderProfile?.getDocType().toString())
        binding.activateSimView.setEditTextCardNumber(orderProfile?.getNationalityId().toString())
        binding.activateSimView.setEditeTextName(orderProfile?.getName().toString())
        binding.activateSimView.setTvSex(orderProfile?.getGender().toString())
        binding.activateSimView.setTvDate(orderProfile?.getDateOfBirth().toString())

    }

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

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

    override fun afterTextChanged(s: Editable?) {
    }

    private fun updateLayoutService(deliverStatus: OrderingManager.DeliverStatus) {
        tmpDeliveryStatus = deliverStatus
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            binding.layoutDelivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            binding.layoutDeliveryLocation.visibility = View.GONE
            binding.ctvDoneSave.visibility = View.GONE
            binding.ctvDoneCancel.visibility = View.GONE
            binding.ctvEditDelivery.visibility = View.GONE
            YesHubNearestActivity.lunchWithResult(context)
            if (binding.ctvEditPickup.visibility == View.GONE && binding.ctvSavePickup.visibility == View.GONE) binding.radioPick.isChecked =
                false
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) showDeliveryLocation(
            address, province
        )

    }

    private fun putDeliveryInfo(isPickup: Boolean = false) {
        object : SeatelJSONObjectRequest(getmContext()) {
            override fun getFunctionName(): String {
                return if (phoneNumber.isEmpty()) {
                    "users/${Constant.DELIVERY_INFO}"
                } else "users/${Constant.DELIVERY_INFO}?phoneNumber=$phoneNumber"
            }

            override fun getMethod(): Int {
                return Request.Method.PUT
            }

            override fun onGetBodyRequest(): String {
                val deliveryAddress = JSONObject()
                try {
                    if (isPickup) {
                        deliveryAddress.put("shopName", shopName)
                        deliveryAddress.put("shopId", shopId)
                        tempShopId = shopId
                    }
                    deliveryAddress.put("address", address)
                    deliveryAddress.put("province", province)
                    deliveryAddress.put("firstName", firstNameDelivery)
                    deliveryAddress.put("lastName", lastNameDelivery)
                    deliveryAddress.put("email", emailDelivery)
                    deliveryAddress.put("phoneNumber", phoneNumberDelivery)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                return deliveryAddress.toString()
            }
        }.execute {
            OrderingManager.getInstance().firstNameSave = firstNameDelivery
            OrderingManager.getInstance().lastNameSave = lastNameDelivery
            OrderingManager.getInstance().emailSave = emailDelivery
            OrderingManager.getInstance().phoneNumberSave = phoneNumberDelivery
            OrderingManager.getInstance().addressSave = address
            OrderingManager.getInstance().provinceSave = province
            if (binding.editTextProvince != null) {
                setDataPickupInfoInput()
                setDataInputDeliveryDefault()
                setDataPickupDisplayInfo()
                setDataDeliveryDisplayInfo()
                checkIsInfoAddressUpdated()
                if (isPickup) visiblePickupAddress()
            }
        }
    }

    private fun getDeliveryInfo() {
        object : SeatelJSONObjectRequest(getmContext()) {
            override fun getFunctionName(): String {
                return if (phoneNumber.isEmpty()) {
                    "users/${Constant.DELIVERY_INFO}"
                } else "users/${Constant.DELIVERY_INFO}?phoneNumber=$phoneNumber"
            }

            override fun getMethod(): Int {
                return Request.Method.GET
            }
        }.execute {
            it as JSONObject
            firstNameDelivery = it.optString("firstName", "")
            lastNameDelivery = it.optString("lastName", "")
            emailDelivery = it.optString("email", "")
            phoneNumberDelivery = it.optString("phoneNumber", "")
            address = it.optString("address", "")
            province = it.optString("province", "")
            strTempAddrss = address
            OrderingManager.getInstance().firstNameSave = firstNameDelivery
            OrderingManager.getInstance().lastNameSave = lastNameDelivery
            OrderingManager.getInstance().emailSave = emailDelivery
            OrderingManager.getInstance().phoneNumberSave = phoneNumberDelivery
            OrderingManager.getInstance().addressSave = address
            OrderingManager.getInstance().provinceSave = province
            setDataInputDeliveryDefault()
            setDataPickupInfoInput()
            if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
                showDeliveryLocation(address, province)
            }
            checkIsInfoAddressUpdated()
        }
    }

    private fun showDeliveryInput() {
        binding.ctvDoneSave.visibility = View.VISIBLE
        binding.ctvEditDelivery.visibility = View.GONE
        binding.viewEditPickup.visibility = View.GONE
        binding.ctvDoneCancel.visibility = View.VISIBLE
        binding.viewShowDelivery.visibility = View.GONE
        binding.viewInputDelivery.visibility = View.VISIBLE
        setDataInputDeliveryDefault()
    }

    private fun setDataInputDeliveryDefault() {
        if (binding.editTextProvince != null) {
            binding.editTextProvince.text = province
            binding.editTextAddress.setText(address)
            binding.editTextFirstName.setText(firstNameDelivery)
            binding.editTextLastName.setText(lastNameDelivery)
            binding.editTextEmail.setText(emailDelivery)
            binding.editTextPhoneNumber.setText(phoneNumberDelivery)
        }
    }

    private fun saveAddressPickupAfterSelectYesHub() {
        if (binding.ctvEditPickup.visibility == View.VISIBLE && firstNameDelivery.isNotEmpty() && lastNameDelivery.isNotEmpty() && emailDelivery.isNotEmpty() && phoneNumberDelivery.isNotEmpty() && shopName.isNotEmpty() && shopId.isNotEmpty()) {

            firstNameDelivery = binding.editTextFirstNamePickup.text.toString()
            lastNameDelivery = binding.editTextLastNamePickup.text.toString()
            emailDelivery = binding.editTextEmailPickup.text.toString()
            phoneNumberDelivery = binding.editTextPhoneNumberPickup.text.toString()

            showInputPickup()
            putDeliveryInfo(true)
        }
    }

    private fun showDeliveryLocation(address: String = "", province: String = "") {

        if (binding.layoutDeliveryLocation == null) return
        binding.ctvSavePickup.visibility = View.GONE
        binding.ctvEditPickup.visibility = View.GONE
        binding.layoutDeliveryLocation.visibility = View.VISIBLE
        binding.radioPick.isChecked = false
        binding.radioDelivery.isChecked = true
        binding.layoutPickUp.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
        binding.layoutDelivery.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)

        binding.imageViewEdit.visibility = View.GONE
        binding.layoutPickLocation.visibility = View.GONE
        binding.tvPickDes.visibility = View.GONE
        binding.viewInputPickup.visibility = View.GONE
        binding.viewShowPickup.visibility = View.GONE


        if (TextUtils.isEmpty(address) && TextUtils.isEmpty(province)) {
            OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
            showDeliveryInput()
        } else {
            OrderingManager.getInstance().locationModel = SeatelShopLocationModel(address, province)

            setDataDeliveryDisplayInfo()
            binding.ctvDoneSave.visibility = View.GONE
            binding.ctvDoneCancel.visibility = View.GONE
            binding.ctvEditDelivery.visibility = View.VISIBLE
            binding.viewShowDelivery.visibility = View.VISIBLE
            binding.viewInputDelivery.visibility = View.GONE
            checkIsInfoAddressUpdated()
        }

    }

    private fun updateData(data: SeatelShopLocationModel, initial: Boolean = false) {
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            OrderingManager.getInstance().deliverStatus = OrderingManager.DeliverStatus.PICKUP

            binding.layoutPickUp.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)
            binding.radioPick.isChecked = true
            binding.imageViewEdit.visibility = View.VISIBLE
            binding.imageViewEdit.setOnClickListener(this)
            binding.layoutPickLocation.visibility = View.VISIBLE
            binding.tvPickDes.visibility = View.VISIBLE

            showInputPickup()
            shopName = data.name
            shopId = data.id
            if (initial) tempShopId = shopId

            binding.layoutDelivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            binding.viewTitleDelivery.setOnClickListener(this)
            binding.radioDelivery.isChecked = false
            binding.layoutDeliveryLocation.visibility = View.GONE

            setDataPickupDisplayInfo()
            binding.tvPickDes.text = data.address
            binding.tvPickLocation.text = data.name
            if (data.address.isEmpty() && data.name.isEmpty()) binding.radioPick.isChecked = false
            if (!initial) saveAddressPickupAfterSelectYesHub()
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
            OrderingManager.getInstance().deliverStatus = OrderingManager.DeliverStatus.DELIVERY

            binding.layoutDelivery.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)
            binding.radioDelivery.isChecked = true
            binding.ctvEditDelivery.visibility = View.VISIBLE
            binding.ctvEditDelivery.setOnClickListener(this)
            binding.layoutDeliveryLocation.visibility = View.VISIBLE

            binding.layoutPickUp.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            binding.viewTitlePickup.setOnClickListener(this)
            binding.radioPick.isChecked = false
            binding.imageViewEdit.visibility = View.GONE
            binding.layoutPickLocation.visibility = View.GONE
            binding.tvPickDes.visibility = View.GONE
            binding.viewInputPickup.visibility = View.GONE
            binding.viewShowPickup.visibility = View.GONE

            if (initial) {
                if (checkIsEmptyAll()) {
                    binding.ctvDoneSave.visibility = View.VISIBLE
                    binding.ctvDoneCancel.visibility = View.VISIBLE
                    binding.ctvEditDelivery.visibility = View.GONE
                    binding.viewInputDelivery.visibility = View.VISIBLE
                    binding.viewShowDelivery.visibility = View.GONE
                } else {
                    binding.ctvDoneSave.visibility = View.GONE
                    binding.ctvDoneCancel.visibility = View.GONE
                    binding.ctvEditDelivery.visibility = View.VISIBLE
                    binding.viewInputDelivery.visibility = View.GONE
                    binding.viewShowDelivery.visibility = View.VISIBLE
                }
            } else {
                binding.ctvDoneSave.visibility = View.GONE
                binding.ctvDoneCancel.visibility = View.GONE
                binding.ctvEditDelivery.visibility = View.VISIBLE
                binding.viewInputDelivery.visibility = View.GONE
                binding.viewShowDelivery.visibility = View.VISIBLE
            }
        }
    }


}