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

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.nivesh.production.partnerOnBoarding.R
import com.nivesh.production.partnerOnBoarding.api.ApiClient
import com.nivesh.production.partnerOnBoarding.databinding.FragmentAlmostThereBinding
import com.nivesh.production.partnerOnBoarding.db.PreferenceManager
import com.nivesh.production.partnerOnBoarding.model.DataX
import com.nivesh.production.partnerOnBoarding.model.request.PartnerRequest
import com.nivesh.production.partnerOnBoarding.model.response.GetAreaDetailByPinResponse
import com.nivesh.production.partnerOnBoarding.model.response.PANResponse
import com.nivesh.production.partnerOnBoarding.model.response.PartnerResponse
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.isValidPinCode
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.showDialogValidation
import com.nivesh.production.partnerOnBoarding.util.Constants.Companion.privacyPolicyLink
import com.nivesh.production.partnerOnBoarding.util.Constants.Companion.tcLink
import com.nivesh.production.partnerOnBoarding.util.ProgressUtil
import com.nivesh.production.partnerOnBoarding.viewModels.OnBoardingViewModel

class AlmostThereFragment : BaseFragment() {
    private var _binding: FragmentAlmostThereBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: OnBoardingViewModel
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAlmostThereBinding.inflate(inflater, container, false)
        return binding.root
    }

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

    private fun init() {

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

        val partnerRequest: PartnerRequest =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arguments?.getSerializable("InputValue", PartnerRequest::class.java)!!
            } else {
                (arguments?.getSerializable("InputValue") as? PartnerRequest)!!
            }

        val arnData: DataX? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("arnData", DataX::class.java)
        } else {
            (arguments?.getSerializable("arnData") as? DataX)!!
        }

        val panResponse: PANResponse? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("panData", PANResponse::class.java)
        } else {
            (arguments?.getSerializable("panData") as? PANResponse)!!
        }

        Log.e("check_arn_Data", arnData.toString() + "\n" + panResponse.toString())
        if (panResponse != null)
            binding.edtDate.setText(panResponse.Result.data.DOB)

        if (arnData?.FullName != null) {
            binding.edtFullName.setText(arnData.FullName)
        } else if (panResponse?.Result?.data?.FullName != null) {
            binding.edtFullName.setText(panResponse.Result.data.FullName)
        } else {
            binding.edtFullName.setText("")
        }

        if (arnData?.Address != null) {
            binding.edtAddressLine1.setText(arnData.Address)
        } else if (panResponse?.Result?.data?.Address1 != null) {
            binding.edtAddressLine1.setText(panResponse.Result.data.Address1)
        } else {
            binding.edtAddressLine1.setText("")
        }

        //TODO: Set Address Line2 Data from Pan
        if (panResponse?.Result?.data?.Address2 != null) {
            binding.edtAddressLine2.setText(panResponse.Result.data.Address2)
        } else {
            binding.edtAddressLine2.setText("")
        }

        if (arnData?.Pincode != null) {
            binding.edtPinCode.setText(arnData.Pincode)
        } else if (panResponse?.Result?.data?.Pincode != null) {
            binding.edtPinCode.setText(panResponse.Result.data.Pincode)
        } else {
            binding.edtPinCode.setText("")
        }

        if (arnData?.City != null) {
            binding.spCity.setText(arnData.City)
        } else if (panResponse?.Result?.data?.City != null) {
            binding.spCity.setText(panResponse.Result.data.City)
        } else {
            binding.spCity.setText("")
        }

        if (arnData?.State != null) {
            binding.spState.setText(arnData.State)
        } else if (panResponse?.Result?.data?.State != null) {
            binding.spState.setText(panResponse.Result.data.State)
        } else {
            binding.spState.setText("")
        }

        binding.edtDate.setOnClickListener {
            Common.datePicker(activity as SignUpActivity, binding.edtDate,false)
        }

        binding.ivInfo.setOnClickListener {
            replaceFragment(
                activity as BaseActivity,
                R.id.signUpContainer,
                QuestionsFragment(),
                "GET STARTED",
                true
            )
        }

        binding.edtFullName.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.tlFullName)
            }
        })

        binding.edtEmail.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.tlEmail)
            }
        })

        binding.edtAddressLine1.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.tlAddressLine1)
            }
        })

        binding.edtPinCode.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.tlPinCode)
            }
        })

        binding.spCity.setOnClickListener {

        }
        binding.spState.setOnClickListener {

        }
        binding.cbCheck.setOnClickListener {

        }

        binding.tvTermsAndCondition.setOnClickListener {
            dialogTCPrivacyPolicy(tcLink.plus("nivesh.html"), getString(R.string.termsAndCondition))
        }

        binding.tvPrivacyPolicy.setOnClickListener {
            dialogTCPrivacyPolicy(privacyPolicyLink.plus("nivesh.html"), getString(R.string.privacy_policy))
        }

        binding.tvAgreement.setOnClickListener {

        }

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

        binding.btnNext.setOnClickListener {
            if (validate()) {
                partnerRequest.Pin = binding.edtPinCode.text.toString()
                partnerRequest.City = binding.spCity.text.toString()
                partnerRequest.State = binding.spState.text.toString()
                partnerRequest.Address1 = binding.edtAddressLine1.text.toString()
                partnerRequest.Address2 = binding.edtAddressLine2.text.toString()
                partnerRequest.Email = binding.edtEmail.text.toString()
                partnerRequest.InterestedProductId = emptyList()
                partnerRequest.Mobile = arguments?.getString("mobile")!!
                partnerRequest.OtherProductName = ""
                partnerRequest.PartnerCode = PreferenceManager((activity as SignUpActivity)).getPartnerCode()
                partnerRequest.PartnerType = getString(R.string.advisory)
                partnerRequest.DateOfIncorporation = Common.getDateFromTimeMills(System.currentTimeMillis())
                Log.e("check_partner", partnerRequest.toString())
                apiPartnerCreation(partnerRequest)
            }
        }

        (activity as SignUpActivity).viewModelOne.getPartnerCreationMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: PartnerResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PartnerResponse::class.java
                )
            Log.e("check_res_partner", res.toString())
            if (res.Status == "success") {
                Toast.makeText(requireActivity(), res.Message, Toast.LENGTH_LONG).show()
                val bundle = Bundle()
                bundle.putSerializable("mobile", arguments?.getString("mobile")!!)
                bundle.putSerializable("email", binding.edtEmail.text.toString())
                bundle.putString("arnType",arguments?.getString("arnType"))
                var fragment: Fragment =
                    if(arguments?.getString("arnType").equals(getString(R.string.advisory),true)){
                        SaveEAgreementFragment()
                    }else{
                        PaymentFragment()
                    }
                fragment.arguments = bundle
                addFragment(
                    activity as BaseActivity,
                    R.id.signUpContainer,
                    fragment,
                    "AlmostThereFragment",
                    true
                )
            }else{
                showDialogValidation((activity as SignUpActivity),res.Message)
            }
        }

        if(panResponse != null){
            pinAPIForCityState(panResponse.Result.data.Pincode)
        }

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

            binding.spCity.setText(res.Result.CityName)
            binding.spState.setText(res.Result.StateName)
        }
    }

    private fun pinAPIForCityState(pinCode: String) {
        try {
            (activity as SignUpActivity).viewModelOne.getAreaDetailByPin(
                pinCode,
                (activity as SignUpActivity)
            )
        } catch (e: Exception) {
            ProgressUtil.hideLoading()
            Log.e("checkPANError", e.message.toString())
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun dialogTCPrivacyPolicy(url: String, type: String) {
        var dialog = Dialog(activity as SignUpActivity)
        dialog.setContentView(R.layout.dialog_t_c)

        val webViewNeedHelp = dialog.findViewById<WebView>(R.id.webViewNeedHelp)
        val txtCancel = dialog.findViewById<TextView>(R.id.txtCancel)
        val btnOk = dialog.findViewById<TextView>(R.id.btnOk)

        val wvTitleTxt: TextView = dialog.findViewById(R.id.wvTitleTxt)
        wvTitleTxt.text = type

        txtCancel.setOnClickListener{dialog.dismiss() }
        btnOk.setOnClickListener{dialog.dismiss() }

        webViewNeedHelp.webViewClient = MyWebViewClient()
        webViewNeedHelp.loadUrl(url)
        webViewNeedHelp.settings.javaScriptEnabled = true
        webViewNeedHelp.settings.domStorageEnabled = true

        dialog.show()
        val lp = WindowManager.LayoutParams()
        lp.copyFrom(dialog.window!!.attributes)
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        dialog.window!!.attributes = lp

    }

    class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            return super.shouldOverrideUrlLoading(view, url)
        }
        override fun onPageFinished(view: WebView, url: String) {}
    }

    private fun apiPartnerCreation(partnerRequest: PartnerRequest) {

        (activity as SignUpActivity).viewModelOne.getPartnerCreateData(
            partnerRequest,
            "",
            (activity as SignUpActivity)
        )

        Log.e("checkRequest", Gson().toJson(partnerRequest).toString())
    }

    private fun validate(): Boolean {
        return if (binding.edtDate.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtDate,
                binding.tlDay,
                getString(R.string.emptyDOB)
            )
        } else if (binding.edtFullName.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtFullName,
                binding.tlFullName,
                getString(R.string.full_name_as_on_pan_card)
            )
        } else if (binding.edtEmail.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtEmail,
                binding.tlEmail,
                getString(R.string.enterEmailAddress)
            )
        } else if (!Common.isValidEmail(binding.edtEmail.text.toString())) { // EditText
            Common.commonErrorMethod(
                binding.edtEmail,
                binding.tlEmail,
                getString(R.string.invalidEmail)
            )
        } else if (binding.edtAddressLine1.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtAddressLine1,
                binding.tlAddressLine1,
                getString(R.string.emptyAddressLine1)
            )
        } else if (binding.edtPinCode.text.toString().isEmpty()) { // EditText
            Common.commonErrorMethod(
                binding.edtPinCode,
                binding.tlPinCode,
                getString(R.string.emptyPinCode)
            )
        } else if (isValidPinCode(binding.edtPinCode.text.toString())) { // EditText
            Common.commonErrorMethod(
                binding.edtPinCode,
                binding.tlPinCode,
                getString(R.string.validPinCode)
            )
        } else if (binding.spCity.text.toString().isEmpty()) { // EditText
            Common.commonSpinnerErrorMethod(
                binding.spCity,
                binding.tlCity,
                getString(R.string.emptyCity)
            )
        } else if (binding.spState.text.toString().isEmpty()) { // EditText
            Common.commonSpinnerErrorMethod(
                binding.spState,
                binding.tlState,
                getString(R.string.emptyState)
            )
        } else if (!binding.cbCheck.isChecked) {
            Common.showDialogValidation(
                (activity as SignUpActivity),
                getString(R.string.termsConditionText)
            )
            return false
        } else return binding.cbCheck.isChecked
    }
}