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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.WindowManager
import androidx.lifecycle.lifecycleScope
import com.android.volley.Response
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.ProfileSharedPreference
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.fragment.OrderPaymentFragment
import com.seatel.mobilehall.ui.home.fragment.OrderPickUpDeliveryFragment
import com.seatel.mobilehall.ui.home.fragment.OrderReviewConfirmFragment
import com.seatel.mobilehall.ui.home.fragment.OrderSummaryFragment
import com.seatel.mobilehall.ui.home.model.SeatelShopLocationModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.FileUtils
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.dialogannouncement.WinAngPavDialog
import com.seatel.mobilehall.util.manager.OrderProfileSingleton
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.view.OrderBottomBarView
import com.theartofdev.edmodo.cropper.CropImage
import com.theartofdev.edmodo.cropper.CropImageView
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import kotlinx.android.synthetic.main.activity_order.*
import kotlinx.android.synthetic.main.activity_updated_sim_profile.*
import kotlinx.android.synthetic.main.fragment_order_pick_up.*
import kotlinx.android.synthetic.main.fragment_order_pick_up.activate_sim_view
import kotlinx.android.synthetic.main.view_activate_buy_sim.view.*
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern

class OrderActivity : BaseActivity(), OrderBottomBarView.OnButtonClick,
    Response.Listener<JSONObject> {

    private var fragment: BaseFragment? = null
    private var isProfileValidated: Boolean = false

    override fun onCheckShipInsurance(isCheck: Boolean) {
        OrderingManager.getInstance().isCheckShimmentInsurance = isCheck
        order_bottom_bar.setTotal(OrderingManager.getInstance().totalSelectedPriceWithInsurance)
    }

    override fun onResponse(response: JSONObject?) {
        val remark = response?.optString("remark")
        OrderingManager.getInstance().orderId = remark?.split("\\|")!![0]
        if (response.has("promotions")) {
            var isShowValentineDayPromotion = false
            val promotions = response.optJSONArray("promotions")
            for (i in 0..(promotions.length() - 1)) {
                if (promotions.optJSONObject(i)
                        .optString("code") == Constant.PROMOTION_CODE_VALENTINE_DAY
                ) {
                    isShowValentineDayPromotion = true
                    break
                } else {
                    isShowValentineDayPromotion = false
                }
            }
            if (isShowValentineDayPromotion) showThanksWinDialog(getString(R.string.message_content_valentine_day))
            else goToRegisterInfoSimCard()
        } else goToRegisterInfoSimCard()
    }

    private fun checkValidateSavePickUpDelivery(section: Int) {
        if (section == 2 && fragment is OrderPickUpDeliveryFragment) {
            (fragment as? OrderPickUpDeliveryFragment)?.checkIsInfoAddressUpdated()

        }
    }

    override fun onClick() {
        if (OrderingManager.getInstance().claimFreeSim || OrderingManager.getInstance().winPromotionFreeSim || OrderingManager.getInstance().totalSelectedPriceWithInsurance == 0.0 && OrderingManager.getInstance().selectedSection == 3) {
            OrderingManager.getInstance().executeOrderPayment(this, "", this)
        } else {
            if (OrderingManager.getInstance().selectedSection == 2 && fragment is OrderPickUpDeliveryFragment && !OrderingManager.getInstance().buyTopUpCard) {
                if (!(fragment as? OrderPickUpDeliveryFragment)?.isValidData()!!) {
                    return
                }

            }
            checkValidateSavePickUpDelivery(OrderingManager.getInstance().selectedSection)
            updateFragment(OrderingManager.getInstance().selectedSection + 1)
        }
    }

    private fun updateFragment(section: Int) {
        order_bottom_bar.hideShowButtonNext(true)
        order_bottom_bar.hideInsuranceView(false)
        SeatelUtils.hideKeyboard(this)
        fragment = null
        fragment = when (section) {
            1 -> {
                if (OrderingManager.getInstance().totalSelectedPriceDevice == 0.0) order_bottom_bar.hideInsuranceView(
                    false
                )
                else order_bottom_bar.hideInsuranceView(true)
                OrderSummaryFragment()
            }

            2 -> {
                OrderPickUpDeliveryFragment()
            }

            3 -> {
                if (order_bottom_bar.isCheckInsurance()) {
                    if (OrderingManager.getInstance().totalSelectedPriceDevice == 0.0) order_bottom_bar.hideInsuranceView(
                        false
                    )
                    else order_bottom_bar.hideInsuranceView(true, true)
                }
                order_bottom_bar.setButtonText(R.string.confirm)
                OrderReviewConfirmFragment()
            }

            4 -> {
                order_bottom_bar.hideShowButtonNext(false)
                OrderPaymentFragment()
            }

            else -> return
        }
        (fragment as? OrderPickUpDeliveryFragment)?.setPhoneNumber(getMainPhoneLogin())

        if (OrderingManager.getInstance().selectedSection < section) { //go next section

            if (section == 3 && (OrderingManager.getInstance().deliverStatus == null)) { // || OrderingManager.getInstance().locationModel.address.isEmpty()) && !OrderingManager.getInstance().isSelectedDelivery) {//if go to section 3 we check section 2 if not choose yet return
                order_bottom_bar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_choose_order_service)).show()
                order_bottom_bar.setButtonText(R.string.next)
                return
            }
            if (section == 3 && (OrderingManager.getInstance().updatedDeliveryAddress || OrderingManager.getInstance().updatedPickupAddress)) {//if go to section 3 we check section 2 if not save delivery yet return
                order_bottom_bar.hideInsuranceView(false)
                if (OrderingManager.getInstance().isSelectedDelivery) SeatelAlertDialog(
                    this,
                    getString(R.string.please_save_delivery)
                ).show()
                else SeatelAlertDialog(this, getString(R.string.please_save_pickup)).show()
                order_bottom_bar.setButtonText(R.string.next)
                return
            }

            if (section == 3 && (OrderingManager.getInstance().locationModel == null || OrderingManager.getInstance().locationModel.address.isEmpty()) && OrderingManager.getInstance().isSelectedDelivery) {//if go to section 3 we check section 2 if not choose yet return
                order_bottom_bar.hideInsuranceView(false)
                if (fragment is OrderPickUpDeliveryFragment) {
                    (fragment as? OrderPickUpDeliveryFragment)?.showValidateFieldOnNextClick()
                }
                order_bottom_bar.setButtonText(R.string.next)
                return
            }


            //validate FirstName
            val ps: Pattern = Pattern.compile("^[a-zA-Z]+$")
            val firstName: Matcher =
                ps.matcher(OrderingManager.getInstance().firstNameSave.toString().trim())
            val bFirstName: Boolean = firstName.matches()
            if (section == 3 && !bFirstName) {
                order_bottom_bar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_enter_valid_first_name)).show()
                order_bottom_bar.setButtonText(R.string.next)
                return
            }

            //Validate LastName
            val lastName: Matcher =
                ps.matcher(OrderingManager.getInstance().lastNameSave.toString().trim())
            val bLastName: Boolean = lastName.matches()
            if (section == 3 && !bLastName) {
                order_bottom_bar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_enter_valid_last_name)).show()
                order_bottom_bar.setButtonText(R.string.next)
                return
            }
            val mFragment = fragment
            supportFragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.activity_slide_in_right, R.anim.activity_slide_out_left)
                .replace(R.id.frame_order_content, mFragment!!).show(mFragment).commit()

            OrderingManager.getInstance().selectedSection = section
            setToolbarTitle(OrderingManager.getInstance().toolbarTitle)
            order_section_view.setSection(OrderingManager.getInstance().selectedSection)
        } else { //go back
            val mFragment = fragment
            supportFragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.activity_slide_in_left, R.anim.activity_slide_out_right)
                .replace(R.id.frame_order_content, mFragment!!).show(mFragment).commit()

            OrderingManager.getInstance().selectedSection = section
            setToolbarTitle(OrderingManager.getInstance().toolbarTitle)
            order_section_view.setSection(OrderingManager.getInstance().selectedSection)
        }
    }


    override fun isShowBackButtonLeft(): Boolean {
        return true
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order)
        activityEnterRightAnimation()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)

        if (OrderingManager.getInstance().claimFreeSim || OrderingManager.getInstance().winPromotionFreeSim || OrderingManager.getInstance().totalSelectedPriceWithInsurance == 0.0) order_section_view.setViewForClaimFreeSim()

        val insurancePrice = OrderingManager.getInstance().totalSelectedPriceDevice
        OrderingManager.getInstance().isCheckShimmentInsurance = false
        if (insurancePrice == 0.0) {
            order_bottom_bar.hideInsuranceView(false)
        } else {
            order_bottom_bar.hideInsuranceView(true)
        }
        order_bottom_bar.setPriceInSurancePhoneDevice(insurancePrice)
        order_bottom_bar.setButtonText(R.string.next)
        if (OrderingManager.getInstance().selectedSection == 3) order_bottom_bar.setButtonText(R.string.confirm)
        order_bottom_bar.setOnButtonClick(this)
        order_bottom_bar.setTotal(OrderingManager.getInstance().totalSelectedPriceWithInsurance)

        order_section_view.setSection(OrderingManager.getInstance().selectedSection)

        supportFragmentManager.beginTransaction()
            .add(R.id.frame_order_content, OrderSummaryFragment()).commit()


    }

    private fun showThanksWinDialog(strDes: String) {
        val dialogWin =
            WinAngPavDialog(this, strDes, false, getString(R.string.happy_valentine_day))
        dialogWin.show()
        dialogWin.setOnDismissListener {
            goToRegisterInfoSimCard()
        }
    }

    private fun goToRegisterInfoSimCard() {
        OrderPaymentSuccessActivity.launch(
            this, OrderingManager.getInstance().getOrderId().split("|")[0], isNoneSeatel()
        )
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                Constant.PICK_UP_YES_HUB_LOCATION -> {
                    OrderingManager.getInstance().locationModel = SeatelShopLocationModel()
                    OrderingManager.getInstance().locationModel = Gson().fromJson(
                        data?.getStringExtra(Constant.SHOP_LOCATION_DATA),
                        SeatelShopLocationModel::class.java
                    )
                }

                Constant.REQUEST_WING -> {

                    if (data != null) {
                        if (data.getBooleanExtra("show_valentine_promotion", false)) {
                            showThanksWinDialog(getString(R.string.message_content_valentine_day))
                        } else goToRegisterInfoSimCard()
                    } else {
                        goToRegisterInfoSimCard()
                    }
                }

                Constant.REQUEST_TAKE_PHOTO -> {
                    setCrop()
                    //  activate_sim_view.doCrop(Constant.RequestCode.REQUEST_CROP_PHOTO)
                }

                Constant.REQUEST_LOAD_PHOTO -> {
                    if (data != null && data.data != null) {
                        val actualImage = FileUtils.from(this, data.data)
                        activate_sim_view.mImageCaptureUri = Uri.fromFile(actualImage)
                        setCrop()

                    }

                }

                CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE -> {
                    val result = CropImage.getActivityResult(data)
                    if (resultCode == Activity.RESULT_OK) {
                        result.uri?.let {
                            val actualImage = FileUtils.from(this, it)
                            lifecycleScope.launch {
                                val mOutputFile = Compressor.compress(
                                    this@OrderActivity, actualImage
                                ) {
                                    resolution(640, 480)
                                    quality(60)
                                    format(Bitmap.CompressFormat.WEBP)

                                }
                                val orderProfile =
                                    OrderProfileSingleton.getInstance(this@OrderActivity)
                                when (activate_sim_view.imageType) {
                                    "front" -> {
                                        orderProfile?.setFrontIdImageUrl(mOutputFile)
                                        activate_sim_view.mOutputFront = mOutputFile.toString()
                                        activate_sim_view.mOutputFileFront = mOutputFile
                                        ProfileSharedPreference.getInstance(this@OrderActivity)?.setFrontId(mOutputFile.toString())
                                    }

                                    "back" -> {
                                        orderProfile?.setBackIdImageUrl(mOutputFile)
                                        activate_sim_view.mOutputBack = mOutputFile.toString()
                                        activate_sim_view.mOutputFileBack = mOutputFile
                                        ProfileSharedPreference.getInstance(this@OrderActivity)?.setBackId(mOutputFile.toString())
                                    }

                                    else -> {
                                        orderProfile?.setPhoto(mOutputFile)
                                        activate_sim_view.mOutputUser = mOutputFile.toString()
                                        activate_sim_view.mOutputFileUser = mOutputFile
                                        ProfileSharedPreference.getInstance(this@OrderActivity)?.setProfileImage(mOutputFile.toString())
                                    }
                                }
                                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
                                activate_sim_view.setImageCrop(bitmap)

                            }
                        }

                    }

                }

                Constant.SCAN_MRZ -> {
                    activate_sim_view.onScanIdCardResult(data!!)
                    // getProfileData(data)
                }
            }

        }
    }


    private fun setCrop() {
        CropImage.activity(activate_sim_view.mImageCaptureUri)
            .setGuidelines(CropImageView.Guidelines.ON).start(this)
    }

    override fun getStringToolbarTitle(): String? {
        return OrderingManager.getInstance().toolbarTitle
    }

    override fun onBackPressed() {
        if (OrderingManager.getInstance().selectedSection == 1) {
            super.onBackPressed()
            activityExitLeftAnimation()
        } else {
            updateFragment(OrderingManager.getInstance().selectedSection - 1)
            order_bottom_bar.setButtonText(R.string.next)
            if (OrderingManager.getInstance().selectedSection == 3) order_bottom_bar.setButtonText(R.string.confirm)
        }
    }

    companion object {
        fun launch(
            context: Context,
            isBuyTopUpCard: Boolean = false,
            isClaimFreeSim: Boolean = false,
            isWinPromotionFreeSim: Boolean = false
        ) {
            OrderingManager.getInstance().buyTopUpCard = isBuyTopUpCard
            OrderingManager.getInstance().claimFreeSim = isClaimFreeSim
            OrderingManager.getInstance().winPromotionFreeSim = isWinPromotionFreeSim
            context.startActivity(Intent(context, OrderActivity::class.java))
        }
    }
}