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

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.button.MaterialButton
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.nivesh.production.partnerOnBoarding.R
import com.nivesh.production.partnerOnBoarding.api.ApiClient
import com.nivesh.production.partnerOnBoarding.databinding.FragmentSignupBinding
import com.nivesh.production.partnerOnBoarding.db.PreferenceManager
import com.nivesh.production.partnerOnBoarding.model.request.PartnerRequest
import com.nivesh.production.partnerOnBoarding.model.request.ValidatePartnerRequest
import com.nivesh.production.partnerOnBoarding.model.response.PartnerDetailResponse
import com.nivesh.production.partnerOnBoarding.model.response.PartnerResponse
import com.nivesh.production.partnerOnBoarding.model.response.ValidatePartnerResponse
import com.nivesh.production.partnerOnBoarding.providerfactory.OnBoardingModelProviderFactory
import com.nivesh.production.partnerOnBoarding.repositories.MainRepository
import com.nivesh.production.partnerOnBoarding.ui.activities.BaseActivity
import com.nivesh.production.partnerOnBoarding.ui.activities.SignUpActivity
import com.nivesh.production.partnerOnBoarding.util.Common
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.isValidMobileNumber
import com.nivesh.production.partnerOnBoarding.util.Constants
import com.nivesh.production.partnerOnBoarding.viewModels.OnBoardingViewModel

class SignUpFragment : BaseFragment() {
    private var _binding: FragmentSignupBinding? = null
    private val binding get() = _binding!!
    private var type: Int? = null
    private var arnType: String = ""
    private lateinit var viewModel: OnBoardingViewModel

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        type = arguments?.getInt("type")
        arnType = arguments?.getString("arnType")!!
        init()
    }

    private fun init() {
        viewModel = ViewModelProvider(
            activity as SignUpActivity,
            OnBoardingModelProviderFactory(MainRepository(ApiClient.getApiClientOne))
        )[OnBoardingViewModel::class.java]

        binding.edtMobileNumber.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(10))
        binding.edtMobileNumber.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Common.removeError(binding.tlMobileNumber)
                if(s.toString().length>=10){
                    binding.btnSignUp.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor((activity as SignUpActivity),R.color.buttonRed))
                    binding.btnSignUp.isEnabled = true
                }else if(s.toString().length<10){
                    binding.btnSignUp.isEnabled = false
                    binding.btnSignUp.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor((activity as SignUpActivity),R.color.buttonLightRed))
                }
            }
        })

        binding.btnSignUp.setOnClickListener {
            if (validate()) {
                val vpr = ValidatePartnerRequest()
                vpr.Mobile = binding.edtMobileNumber.text.toString().trim()
                (activity as SignUpActivity).viewModelOne.getPartnerValidate(
                    vpr,
                    "",
                    (activity as SignUpActivity)
                )
            }
        }

        (activity as SignUpActivity).viewModelOne.getPartnerCreationMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val cretePartnerResponse: PartnerResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PartnerResponse::class.java
                )
            if (cretePartnerResponse.Status ==  (activity as SignUpActivity).getString(R.string.successText)) {
                setUpOTPFragment(cretePartnerResponse.Result.PartnerCode)
            } else {
                Common.showDialogValidation(
                    (activity as SignUpActivity),
                    cretePartnerResponse.Message
                )
            }
        }

        (activity as SignUpActivity).viewModelOne.getValidatePartnerMutableData.observe(
            viewLifecycleOwner
        ) { response ->

            val validatePartnerResponse: ValidatePartnerResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    ValidatePartnerResponse::class.java
                )

            if (validatePartnerResponse.Status == (activity as SignUpActivity).getString(R.string.successText)) {
                if (validatePartnerResponse.Result.IsPartialRegistered) {
                    PreferenceManager(activity as SignUpActivity).setPartnerCode(
                        validatePartnerResponse.Result.PartnerCode)

                    checkPartnerDetail(validatePartnerResponse.Result.PartnerCode)

                } else {
                    val partnerRequest = PartnerRequest()
                    partnerRequest.Mobile = binding.edtMobileNumber.text.toString().trim()
                    partnerRequest.PartnerType = arnType
                    partnerRequest.DateOfIncorporation =
                        Common.getDateFromTimeMills(System.currentTimeMillis())
                    //GsonBuilder().create().toJson(this, PartnerRequest::class.java)
                    (activity as SignUpActivity).viewModelOne.getPartnerCreateData(
                        partnerRequest,
                        "",
                        (activity as SignUpActivity)
                    )
                }
            }else if(validatePartnerResponse.Status == "error") {
                Common.showDialogValidation((activity as SignUpActivity),validatePartnerResponse.Message)
            }
        }

        (activity as SignUpActivity).viewModelOne.getPartnerDetailMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val partnerDetailResponse: PartnerDetailResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PartnerDetailResponse::class.java
                )
            if(partnerDetailResponse.Status == getString(R.string.successText)){
                if(partnerDetailResponse.Result.Step == 1){
                    setUpOTPFragment(PreferenceManager((activity as SignUpActivity)).getPartnerCode())
                }else if(partnerDetailResponse.Result.Step != 1){
                    Log.e("check_otp_res", response?.data.toString())
                    val bundle = Bundle()
                    bundle.putString("mobile", partnerDetailResponse.Result.Mobile)
                    bundle.putString("arnType", arguments?.getString("arnType"))
                    bundle.putSerializable("partnerResponse",partnerDetailResponse)
                    var fragment = Fragment()
                    if (type == 4) {
                        when (partnerDetailResponse.Result.Step) {
                            2 -> fragment = GetStartedFragment()
                            3 -> fragment = AlmostThereFragment()
                            4 -> fragment = SaveEAgreementFragment()
                        }
                    } else if (type == 3) {
                       fragment = NewDistributorSignStepOne()
                    }

                    fragment.arguments = bundle

                    addFragment(
                        activity as BaseActivity,
                        R.id.signUpContainer,
                        fragment,
                        "GET STARTED",
                        true
                    )
                }
            }
        }
    }

    private fun checkPartnerDetail(partnerCode: String) {
        (activity as SignUpActivity).viewModelOne.getPartnerDetailData(
            partnerCode,
            Constants.accessKey,
            (activity as SignUpActivity)
        )
    }

    private fun setUpOTPFragment(partnerCode: String) {
        val bundle = Bundle()
        bundle.putInt("type", type!!)
        bundle.putString("mobile", binding.edtMobileNumber.text.toString().trim())
        bundle.putString("arnType", arguments?.getString("arnType")!!)
        bundle.putString("partnerCode", partnerCode)
        PreferenceManager(activity as SignUpActivity).setPartnerCode(partnerCode)
        val fragment = OTPFragment()
        fragment.arguments = bundle

        addFragment(
            activity as BaseActivity,
            R.id.signUpContainer,
            fragment,
            "OTP",
            true
        )
    }

    private fun validate(): Boolean {
        return if (binding.edtMobileNumber.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtMobileNumber,
                binding.tlMobileNumber,
                getString(R.string.emptyMobileNumber)
            )
        } else if (!isValidMobileNumber(binding.edtMobileNumber.text.toString())) { // EditText
            Common.commonErrorMethod(
                binding.edtMobileNumber,
                binding.tlMobileNumber,
                getString(R.string.inValidMobileNumber)
            )
        } else if (!Common.isIndianMobileNo(binding.edtMobileNumber.text.toString())) { // EditText
            Common.commonErrorMethod(
                binding.edtMobileNumber,
                binding.tlMobileNumber,
                getString(R.string.inValidIndianMobileNumber)
            )
        } else {
            return true
        }
    }
}