package com.nivesh.production.partnerOnBoarding.ui.fragments

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.Log
import android.view.*
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.google.gson.Gson
import com.nivesh.production.partnerOnBoarding.R
import com.nivesh.production.partnerOnBoarding.databinding.FragmentSaveEAgreementBinding
import com.nivesh.production.partnerOnBoarding.db.PreferenceManager
import com.nivesh.production.partnerOnBoarding.model.request.SendOTPRequest
import com.nivesh.production.partnerOnBoarding.model.response.SendOTPResponse
import com.nivesh.production.partnerOnBoarding.model.response.ValidateOTPResponse
import com.nivesh.production.partnerOnBoarding.ui.activities.RegisterActivity
import com.nivesh.production.partnerOnBoarding.ui.activities.SignUpActivity
import com.nivesh.production.partnerOnBoarding.util.Common
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class SaveEAgreementFragment : BaseFragment() {
    private var _binding: FragmentSaveEAgreementBinding? = null
    private val binding get() = _binding!!
    private lateinit var dialog: Dialog

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSaveEAgreementBinding.inflate(inflater, container, false)
        return binding.root
    }

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

    @SuppressLint("SetTextI18n")
    private fun init() {

        binding.header.tvTitle.text = "AGREEMENT"

        binding.btnAgree.setOnClickListener {
            smsAPI()
        }

        (activity as SignUpActivity).viewModelOne.getSaveEAgreementMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: ValidateOTPResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    ValidateOTPResponse::class.java
                )

            if (res.Status == getString(R.string.successText)) {
                if (dialog.isShowing) dialog.cancel()
                showConfirmDialog(res.Message)
            } else if (res.Status == "error") {
                Common.showDialogValidation((activity as SignUpActivity), res.Message)
            }
            Log.e("check_otp_res", response?.data.toString())
        }

        binding.header.ivBack.setOnClickListener{
            (activity as SignUpActivity).onBackPressedDispatcher.onBackPressed()
        }

        (activity as SignUpActivity).viewModelOne.getSendOTPSaveEAgreementMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            Log.e("check_res_otp", response?.data.toString())
            if(response!=null) {
                val res: SendOTPResponse =
                    Gson().fromJson(
                        response.data.toString(),
                        SendOTPResponse::class.java
                    )
                if (res.Status ==getString(R.string.successText)) {
                    dialogOTP()
                }
            }
        }
    }

    private fun showConfirmDialog(message: String) {
        val builder = AlertDialog.Builder(activity)
        builder.setMessage(message)
        builder.setCancelable(false)
        if (activity != null) {
            builder.setPositiveButton(getString(R.string.Ok)) { _, _ ->
                val openIntent = Intent(
                    (activity as SignUpActivity),
                    RegisterActivity::class.java
                )
                openIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                (activity as SignUpActivity).startActivity(openIntent)
            }
        }
        builder.show()
    }

    @SuppressLint("SetTextI18n")
    private fun dialogOTP() {

        dialog = Dialog(activity as SignUpActivity)
        dialog.setContentView(R.layout.agreement_otp)

        val txtDigit: TextView = dialog.findViewById(R.id.txtDigit)
        val btnSubmit: MaterialButton = dialog.findViewById(R.id.btnSubmit)
        val edtOTP1: TextInputEditText = dialog.findViewById(R.id.edtOTP1)
        val edtOTP2: TextInputEditText = dialog.findViewById(R.id.edtOTP2)
        val edtOTP3: TextInputEditText = dialog.findViewById(R.id.edtOTP3)
        val edtOTP4: TextInputEditText = dialog.findViewById(R.id.edtOTP4)
        val edtOTP5: TextInputEditText = dialog.findViewById(R.id.edtOTP5)
        val edtOTP6: TextInputEditText = dialog.findViewById(R.id.edtOTP6)
        val tlOTP1: TextInputLayout = dialog.findViewById(R.id.tlOTP1)
        val tlOTP2: TextInputLayout = dialog.findViewById(R.id.tlOTP2)
        val tlOTP3: TextInputLayout = dialog.findViewById(R.id.tlOTP3)
        val tlOTP4: TextInputLayout = dialog.findViewById(R.id.tlOTP4)
        val tlOTP5: TextInputLayout = dialog.findViewById(R.id.tlOTP5)
        val tlOTP6: TextInputLayout = dialog.findViewById(R.id.tlOTP6)
        val txtResendOTP: TextView = dialog.findViewById(R.id.txtResendOTP)

        edtOTP1.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))
        edtOTP2.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))
        edtOTP3.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))
        edtOTP4.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))
        edtOTP5.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))
        edtOTP6.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(1))

        edtOTP1.addTextChangedListener(
            GenericTextWatcher(
                edtOTP1,
                edtOTP2
            )
        )
        edtOTP2.addTextChangedListener(
            GenericTextWatcher(
                edtOTP2,
                edtOTP3
            )
        )
        edtOTP3.addTextChangedListener(
            GenericTextWatcher(
                edtOTP3,
                edtOTP4
            )
        )
        edtOTP4.addTextChangedListener(
            GenericTextWatcher(
                edtOTP4,
                edtOTP5
            )
        )
        edtOTP5.addTextChangedListener(
            GenericTextWatcher(
                edtOTP5,
                edtOTP6
            )
        )
        edtOTP6.addTextChangedListener(
            GenericTextWatcher(
                edtOTP6,
                null
            )
        )

        edtOTP1.setOnKeyListener(OTPFragment.GenericKeyEvent(edtOTP1, null))
        edtOTP2.setOnKeyListener(
            GenericKeyEvent(
                edtOTP2,
                edtOTP1
            )
        )
        edtOTP3.setOnKeyListener(
            GenericKeyEvent(
                edtOTP3,
                edtOTP2
            )
        )
        edtOTP4.setOnKeyListener(
            OTPFragment.GenericKeyEvent(
                edtOTP4,
                edtOTP3
            )
        )
        edtOTP5.setOnKeyListener(
            OTPFragment.GenericKeyEvent(
                edtOTP5,
                edtOTP4
            )
        )
        edtOTP6.setOnKeyListener(
            OTPFragment.GenericKeyEvent(
                edtOTP6,
                edtOTP5
            )
        )

        txtDigit.text =
            getString(R.string.sixDigitOTP) + " " + arguments?.getString("email").toString()

        txtResendOTP.setOnClickListener{
            if(dialog.isShowing) dialog.cancel()

        }

        btnSubmit.setOnClickListener {

            if (edtOTP1.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP1,
                    tlOTP1,
                    ""
                )
            } else if (edtOTP2.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP2,
                    tlOTP2,
                    ""
                )
            } else if (edtOTP3.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP3,
                    tlOTP3,
                    ""
                )
            } else if (edtOTP4.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP4,
                    tlOTP4,
                    ""
                )
            } else if (edtOTP5.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP5,
                    tlOTP5,
                    ""
                )
            } else if (edtOTP6.text.toString().isEmpty()) { // EditText
                Common.commonErrorMethod(
                    edtOTP6,
                    tlOTP6,
                    ""
                )
            } else {
                apiVerifyOTP(
                    edtOTP1.text.toString().plus(
                        edtOTP2.text.toString().plus(
                            edtOTP3.text.toString().plus(
                                    edtOTP4.text.toString().plus(
                                        edtOTP5.text.toString().plus(
                                            edtOTP6.text.toString()))
                            )
                        )
                    )
                )
            }
        }

        if(!dialog.isShowing) dialog.show()

        val window: Window = dialog.window!!
        window.setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT)
    }

    private fun apiVerifyOTP(otp: String) {
        val obj = JSONObject()
        obj.put("SubBrokerCode", PreferenceManager((activity as SignUpActivity)).getPartnerCode())
        obj.put("OTP", otp)
        obj.put("OTPGenerationDate", Common.getDateFromTimeMills(System.currentTimeMillis()))
        obj.put("FinancialYear", "")

        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body: RequestBody = obj.toString().toRequestBody(mediaType)

        (activity as SignUpActivity).viewModelOne.getSaveEAgreement(
            body,
            "",
            (activity as SignUpActivity)
        )
    }

    private fun smsAPI() {
        val sendOTPRequest = SendOTPRequest()
        sendOTPRequest.AMCID = ""
        sendOTPRequest.CommunicationValue = arguments?.getString("email").toString()
        sendOTPRequest.Mode = "email"
        sendOTPRequest.MsgState = "EagreementOTP"
        sendOTPRequest.Name = "Manoj Singh"
        sendOTPRequest.ProductId = 1
        sendOTPRequest.UserRole = 3
        sendOTPRequest.UserId = PreferenceManager((activity as SignUpActivity)).getPartnerCode()
        (activity as SignUpActivity).viewModelOne.getSaveEAgreementSendOTP(
            sendOTPRequest,
            "",
            (activity as SignUpActivity)
        )
    }

    class GenericKeyEvent internal constructor(
        private val currentView: EditText,
        private val previousView: EditText?
    ) : View.OnKeyListener {
        override fun onKey(p0: View?, keyCode: Int, event: KeyEvent?): Boolean {
            if (event!!.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL && currentView.id != R.id.edtOTP1 && currentView.text.isEmpty()) {
                //If current is empty then previous EditText's number will also be deleted
                previousView!!.text = null
                previousView.requestFocus()
                return true
            }
            return false
        }
    }

    class GenericTextWatcher internal constructor(
        private val currentView: View,
        private val nextView: View?
    ) : TextWatcher {
        override fun afterTextChanged(editable: Editable) { // TODO Auto-generated method stub
            val text = editable.toString()
            when (currentView.id) {
                R.id.edtOTP1 -> if (text.length == 1) nextView!!.requestFocus()
                R.id.edtOTP2 -> if (text.length == 1) nextView!!.requestFocus()
                R.id.edtOTP3 -> if (text.length == 1) nextView!!.requestFocus()
                R.id.edtOTP4 -> if (text.length == 1) nextView!!.requestFocus()
                R.id.edtOTP5 -> if (text.length == 1) nextView!!.requestFocus()
                //You can use EditText4 same as above to hide the keyboard
            }
        }

        override fun beforeTextChanged(
            arg0: CharSequence,
            arg1: Int,
            arg2: Int,
            arg3: Int
        ) {
        }

        override fun onTextChanged(
            arg0: CharSequence,
            arg1: Int,
            arg2: Int,
            arg3: Int
        ) {
        }
    }
}