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.os.Bundle
import android.view.WindowManager
import androidx.lifecycle.lifecycleScope
import com.android.volley.Response
import com.canhub.cropper.CropImageContract
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ActivityOrderBinding
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.OrderingManager
import com.seatel.mobilehall.util.view.OrderBottomBarView
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.coroutines.launch
import org.json.JSONObject
import java.util.regex.Matcher
import java.util.regex.Pattern

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

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

    override fun onCheckShipInsurance(isCheck: Boolean) {
        OrderingManager.getInstance().isCheckShimmentInsurance = isCheck
        binding.orderBottomBar.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) {
        binding.orderBottomBar.hideShowButtonNext(true)
        binding.orderBottomBar.hideInsuranceView(false)
        SeatelUtils.hideKeyboard(this)
        fragment = null
        fragment = when (section) {
            1 -> {
                if (OrderingManager.getInstance().totalSelectedPriceDevice == 0.0) binding.orderBottomBar.hideInsuranceView(
                    false
                )
                else binding.orderBottomBar.hideInsuranceView(true)
                OrderSummaryFragment()
            }

            2 -> {
                OrderPickUpDeliveryFragment()
            }

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

            4 -> {
                binding.orderBottomBar.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
                binding.orderBottomBar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_choose_order_service)).show()
                binding.orderBottomBar.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
                binding.orderBottomBar.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()
                binding.orderBottomBar.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
                binding.orderBottomBar.hideInsuranceView(false)
                if (fragment is OrderPickUpDeliveryFragment) {
                    (fragment as? OrderPickUpDeliveryFragment)?.showValidateFieldOnNextClick()
                }
                binding.orderBottomBar.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) {
                binding.orderBottomBar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_enter_valid_first_name)).show()
                binding.orderBottomBar.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) {
                binding.orderBottomBar.hideInsuranceView(false)
                SeatelAlertDialog(this, getString(R.string.please_enter_valid_last_name)).show()
                binding.orderBottomBar.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)
            binding.orderSectionView.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)
            binding.orderSectionView.setSection(OrderingManager.getInstance().selectedSection)
        }
    }


    override fun isShowBackButtonLeft(): Boolean {
        return true
    }

    override fun getViewBinding(): ActivityOrderBinding {
        return ActivityOrderBinding.inflate(layoutInflater)
    }


    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) binding.orderSectionView.setViewForClaimFreeSim()

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

        binding.orderSectionView.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 val cropImage = registerForActivityResult(CropImageContract()) { result ->
        if (result.isSuccessful) {
            result.uriContent?.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)*/

                }
            }
        } else {
            // An error occurred.
            val exception = result.error
            // Handle the error.

        }
    }

    fun setCrop() {
       /* cropImage.launch(

            CropImageContractOptions(
                uri = activate_sim_view.mImageCaptureUri,
                cropImageOptions = CropImageOptions(
                    guidelines = CropImageView.Guidelines.ON,
                    aspectRatioX = 4,
                    aspectRatioY = 3,
                    fixAspectRatio = true
                )
            )
        )*/

        /* CropImage.activity(mImageCaptureUri)
             .setGuidelines(CropImageView.Guidelines.ON)
             .setAspectRatio(4, 3)
             .start(this)*/
    }


    /* 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)
            binding.orderBottomBar.setButtonText(R.string.next)
            if (OrderingManager.getInstance().selectedSection == 3) binding.orderBottomBar.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))
        }
    }
}