package com.seatel.mobilehall.ui.login.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.android.volley.Request
import com.android.volley.Response
import com.canhub.cropper.CropImageContract
import com.canhub.cropper.CropImageContractOptions
import com.canhub.cropper.CropImageOptions
import com.canhub.cropper.CropImageView
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.databinding.ActivityUpdatedSimProfileBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.login.model.UploadImageResponse
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.FileUtils
import com.seatel.mobilehall.util.MultipartEntityRequest
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.BottomSheetFaceScanFragment
import com.seatel.mobilehall.util.customview.ErrorHandleView
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.io.File

class UpdatedSimProfileActivity : BaseActivity<ActivityUpdatedSimProfileBinding>() {

    private var imageFrontFileName = ""
    private var imageBackFileName = ""
    private var imageUserFileName = ""
    private var phoneNumber = ""
    private var isPostingRequest = false

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //  setContentView(R.layout.activity_updated_sim_profile)
        activityEnterRightAnimation()
        binding.activateSimView.layoutUploadUser().setOnClickListener {
            binding.activateSimView.imageType = "user"
            val bottomSheetFaceScanFragment = BottomSheetFaceScanFragment()
            bottomSheetFaceScanFragment.show(
                this.supportFragmentManager, "ShowBottomSheetFaceScanDialog"
            )
        }
        if (intent.hasExtra(Constant.PHONE_NUMBER)) phoneNumber =
            intent.getStringExtra(Constant.PHONE_NUMBER).toString()
        binding.ctvPhoneNumberHeader.text = SeatelUtils.phoneNumberFormat(phoneNumber)
        binding.activateSimView.displayForUpdateSimProfile()
        binding.buttonDone.setOnClickListener {
            uploadImage()
        }
    }


    private fun postInfo() {

        if (binding.activateSimView.mOutputFileBack != null && imageBackFileName.isEmpty()) return
        if (binding.activateSimView.mOutputFileFront != null && imageFrontFileName.isEmpty()) return
        if (binding.activateSimView.mOutputFileUser != null && imageUserFileName.isEmpty()) return
        if (isPostingRequest) return
        isPostingRequest = true

        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        object : SeatelJSONObjectRequest(this@UpdatedSimProfileActivity) {


            override fun getFunctionName(): String {
                return "seatel/$phoneNumber/modify"
            }

            override fun onGetBodyRequest(): String {
                val profile = JSONObject()
                profile.put("certId", binding.activateSimView.getIdCertType())
                profile.put(
                    "certNum", binding.activateSimView.getEditTextCardNumber()
                )
                profile.put("name", binding.activateSimView.getEditTextName())
                profile.put("certName", binding.activateSimView.getCertificationNamePost())
                profile.put("gender", binding.activateSimView.getGenderKeyPost())
                profile.put("dateOfBirth", binding.activateSimView.dateOfBirth)
                profile.put("dateOfExpiry", binding.activateSimView.dateOfExpiry)
                profile.put("nationality", binding.activateSimView.nationality)
                profile.put("frontIdImageUrl", imageFrontFileName)
                profile.put("backIdImageUrl", imageBackFileName)
                profile.put("photoUrl", imageUserFileName)

                return profile.toString()
            }

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


        }.setOnErrorListener {
            isPostingRequest = false
            binding.errorView.visibility = View.GONE
            SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(it)).show()
        }.execute {
            SeatelAlertDialog(
                this, getString(R.string.meesage_modify_profile_sim_success)
            ).setPositiveButton("Yes") { dialog, _ ->
                dialog?.dismiss()
                gotoMainScreen()
                finish()
                activityExitDownAnimation()
            }.show()
            binding.errorView.visibility = View.GONE
            isPostingRequest = false
        }
    }

    private fun uploadImage() {
        if (!isValidData()) {
            return
        }

        if (binding.activateSimView.mOutputFileBack != null) {
            upload(Response.Listener {
                imageBackFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileBack!!)
        }

        if (binding.activateSimView.mOutputFileFront != null) {
            upload(Response.Listener {
                imageFrontFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileFront!!)
        }

        if (binding.activateSimView.mOutputFileUser != null) {
            upload(Response.Listener {
                imageUserFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileUser!!)
        }

    }

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

        if (TextUtils.isEmpty(binding.activateSimView.getTvSex())) {
            SeatelAlertDialog.with(this, "Please select your gender.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileFront == null) {
            SeatelAlertDialog.with(this, "Please take picture ID front.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileBack == null) {
            SeatelAlertDialog.with(this, "Please take picture ID back.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileUser == null) {
            SeatelAlertDialog.with(this, "Please take your photo.").show()
            return false
        }
        return true
    }

    private fun getUploadResponseModel(data: String): UploadImageResponse {
        return Gson().fromJson(data, UploadImageResponse::class.java)
    }

    private fun upload(response: Response.Listener<String>, file: File) {
        val multi = MultipartEntityRequest.with(this).setType(Constant.ANY).setFile(file)
        multi.setOnErrorListener {
            if (it.networkResponse.statusCode == 413) {
                SeatelAlertDialog.with(this, "Request Entity Too Large").show()
            }/*SeatelAlertDialog.with(this, "Please check your internet connection and try again!")
                .show()*/
        }
        multi.upLoadImage(response)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == Constant.REQUEST_GELLARY) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission was granted, proceed to open the gallery
                launchGalleryIntent()
            } else {
                // Permission denied, handle accordingly (e.g., show a message to the user)
                Snackbar.make(
                    findViewById(android.R.id.content),
                    "Permission denied. You can enable it in settings.",
                    Snackbar.LENGTH_INDEFINITE
                ).setAction("Settings") {
                    // Open app settings
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.parse("package:${this.packageName}")
                    startActivity(intent)
                }.show()
            }
        }
    }

    private fun launchGalleryIntent() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, Constant.REQUEST_LOAD_PHOTO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) when (requestCode) {

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

            Constant.REQUEST_LOAD_PHOTO -> {
                if (data != null && data.data != null) {
                    val actualImage = FileUtils.from(this, data.data)
                    binding.activateSimView.mImageCaptureUri = Uri.fromFile(actualImage)
                    setCrop()/*   GlobalScope.launch {
                               val file =
                                   Compressor.compress(this@UpdatedSimProfileActivity, actualImage) {
                                       resolution(640, 480)
                                       quality(90)
                                       format(Bitmap.CompressFormat.WEBP)

                                   }

                           }*/

                    //   binding.activateSimView.doCrop(Constant.RequestCode.REQUEST_CROP_PHOTO)

                }

            }

            /*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@UpdatedSimProfileActivity, actualImage
                             ) {
                                 resolution(640, 480)
                                 quality(90)
                                 format(Bitmap.CompressFormat.WEBP)

                             }

                             when (binding.activateSimView.imageType) {
                                 "front" -> binding.activateSimView.mOutputFileFront = mOutputFile
                                 "back" -> binding.activateSimView.mOutputFileBack = mOutputFile
                                 else -> binding.activateSimView.mOutputFileUser = mOutputFile
                             }
                             val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
                             binding.activateSimView.setImageCrop(bitmap)

                         }
                     }

                 }*//*

            }*/

            Constant.SCAN_MRZ -> {
                binding.activateSimView.onScanIdCardResult(data!!)
                onScanCardResult(data)
            }

            Constant.SCAN_FACE -> {
                data?.let {
                    val imgPath = it.getStringExtra("faceImage") ?: return
                    val file = File(imgPath)
                    binding.activateSimView.mImageCaptureUri = Uri.fromFile(file)
                    setCrop()
                    //   binding.activateSimView.image_view_user.visibility = View.VISIBLE
                    //   Glide.with(this).load(file).into(binding.activateSimView.image_view_user)
                    Log.d("TAG::>>>", "onActivityResult: $file ")

                }
            }
        }
    }

    private fun onScanCardResult(data: Intent) {
        val imgPath = data.getStringExtra("imagePath") ?: return
        val file = File(imgPath)
        binding.activateSimView.mImageCaptureUri = Uri.fromFile(file)
        binding.activateSimView.imageType = "front"
        setCrop()

    }

    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@UpdatedSimProfileActivity, actualImage
                    ) {
                        resolution(640, 480)
                        quality(90)
                        format(Bitmap.CompressFormat.WEBP)

                    }

                    when (binding.activateSimView.imageType) {
                        "front" -> binding.activateSimView.mOutputFileFront = mOutputFile
                        "back" -> binding.activateSimView.mOutputFileBack = mOutputFile
                        else -> binding.activateSimView.mOutputFileUser = mOutputFile
                    }
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
                    binding.activateSimView.setImageCrop(bitmap)

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

        }
    }


    private fun setCrop() {
        cropImage.launch(
            CropImageContractOptions(
                uri = binding.activateSimView.mImageCaptureUri,
                cropImageOptions = CropImageOptions(
                    guidelines = CropImageView.Guidelines.ON,
                    aspectRatioX = 4,
                    aspectRatioY = 3,
                    fixAspectRatio = true
                )
            )
        )
        /*CropImage.activity(binding.activateSimView.mImageCaptureUri)
            .setGuidelines(CropImageView.Guidelines.ON).start(this)*/
    }

    override fun onBackPressed() {
        super.onBackPressed()
        super.activityExitLeftAnimation()
    }

    override fun getToolbarTitle(): String {
        return getString(R.string.update_profile)
    }

    companion object {
        fun launch(context: Context, phoneNumber: String) {
            val intent = Intent(context, UpdatedSimProfileActivity::class.java)
            intent.putExtra(Constant.PHONE_NUMBER, phoneNumber)
            context.startActivity(intent)
        }
    }

}
