package com.nivesh.production.niveshfd.fd.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.nivesh.production.niveshfd.R
import com.nivesh.production.niveshfd.databinding.FragmentNiveshfdStepFourBinding
import com.nivesh.production.niveshfd.fd.adapter.CustomerListAdapter
import com.nivesh.production.niveshfd.fd.db.PreferenceManager
import com.nivesh.production.niveshfd.fd.model.*
import com.nivesh.production.niveshfd.fd.ui.activity.NiveshFdMainActivity
import com.nivesh.production.niveshfd.fd.util.Common
import com.nivesh.production.niveshfd.fd.util.Common.Companion.showDialogValidation
import com.nivesh.production.niveshfd.fd.util.Resource

class StepFourNiveshFDFragment : Fragment() {

    private var _binding: FragmentNiveshfdStepFourBinding? = null
    private val binding get() = _binding!!

    private lateinit var listOfCustomer: MutableList<GetCodes>
    private var selectedList: String = ""
    private var payUrl: String = ""
    private var value: String = ""
    private var checkNRI: Boolean = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentNiveshfdStepFourBinding.inflate(inflater, container, false)
        return binding.root
    }

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

        if (PreferenceManager(activity as NiveshFdMainActivity).getLoginRole() == 5) {
            binding.btnNext.text = getString(R.string.pay)
            binding.btnNext.setBackgroundColor(
                ResourcesCompat.getColor(
                    resources,
                    R.color.green,
                    null
                )
            )
        } else {
            binding.btnNext.text = getString(R.string.viewOrder)
            binding.btnNext.setBackgroundColor(
                ResourcesCompat.getColor(
                    resources,
                    R.color.red,
                    null
                )
            )
        }
        checkNRI = true
        binding.btnNext.setOnClickListener {
            selectedList = ""
            for (getCodes in listOfCustomer) {
                if (getCodes.isSelected) {
                    selectedList = if (selectedList.isEmpty()) {
                        getCodes.Value
                    } else {
                        if (getCodes.Value.contains("outside of india", true)) {
                            checkNRI = getCodes.isSelected
                        }
                        selectedList.plus(",").plus(getCodes.Value)
                    }
                }
            }
            if (validated()) {
                if (PreferenceManager(activity as NiveshFdMainActivity).getLoginRole() == 5) {
                    val saveFDOtherDataRequest = SaveFDOtherDataRequest()
                    saveFDOtherDataRequest.FDProvider = getString(R.string.bajaj)
                    saveFDOtherDataRequest.UniqueId = (activity as NiveshFdMainActivity).uniqueId
                    saveFDOtherDataRequest.Values = selectedList
                    saveFDOtherDataRequest.NiveshClientCode =
                        (activity as NiveshFdMainActivity).getClientDetailsResponse.ObjectResponse?.clientDetails?.clientMasterMFD?.CLIENT_CODE
                    saveFDOtherData(saveFDOtherDataRequest, payUrl, value)
                } else {
                    // go to view order
                }
            }
        }

        binding.btnBack.setOnClickListener {
            if ((activity as NiveshFdMainActivity).stepCount == 4) {
                (activity as NiveshFdMainActivity).binding.viewPager.currentItem = 2
            } else {
                (activity as NiveshFdMainActivity).binding.viewPager.currentItem = 1
            }
        }

        customerListApi()
    }

    private fun customerListApi() {
        val getCodeRequest = GetCodeRequest()
        getCodeRequest.ProductName = getString(R.string.bajajFD)
        getCodeRequest.Category = getString(R.string.customerCategory)
        getCodeRequest.Language = getString(R.string.language)
        getCodeRequest.InputValue = ""
        (activity as NiveshFdMainActivity).viewModel.customerListApi(
            getCodeRequest,
            PreferenceManager(activity as NiveshFdMainActivity).getToken(),
            activity as NiveshFdMainActivity
        )
        (activity as NiveshFdMainActivity).viewModel.customerListMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            when (response) {
                is Resource.Success -> {
                    Log.e("customerListApi", " response -->${response.data.toString()}")
                    val getCodeResponse: GetCodeResponse =
                        Gson().fromJson(response.data?.toString(), GetCodeResponse::class.java)
                    getCodeResponse.Response.StatusCode.let { code ->
                        when (code) {
                            200 -> {
                                if (getCodeResponse.Response.GetCodesList.isNotEmpty()) {
                                    listOfCustomer = getCodeResponse.Response.GetCodesList
                                    setUpRecyclerView(listOfCustomer)
                                }
                            }
                            //  650 -> refreshToken()
                            else -> {
                                if (getCodeResponse.Response.Errors.isNotEmpty()) {
                                    showDialogValidation(
                                        activity as NiveshFdMainActivity,
                                        getCodeResponse.Response.Errors[0].ErrorMessage
                                    )
                                } else {
                                    showDialogValidation(
                                        activity as NiveshFdMainActivity,
                                        "".plus(getCodeResponse.Response.Message)
                                    )
                                }
                            }
                        }
                    }
                }

                is Resource.Error -> {
                    response.message?.let { message ->
                        showDialogValidation(activity as NiveshFdMainActivity, message)
                    }
                }
                is Resource.Loading -> {

                }
                is Resource.DataError -> {

                }
            }
        }
    }

    private fun validated(): Boolean {
        return if (!checkNRI) {
            showDialogValidation(
                activity as NiveshFdMainActivity,
                getString(R.string.validNRI)
            )
            false
        } else if (!binding.checkBox.isChecked) {
            showDialogValidation(
                activity as NiveshFdMainActivity,
                resources.getString(R.string.validTermsConditions)
            )
            false
        } else {
            true
        }
    }

    private fun saveFDOtherData(data: SaveFDOtherDataRequest, payUrl: String, value: String) {
        //  ProgressUtil.showLoading(activity as NiveshFdMainActivity)
        (activity as NiveshFdMainActivity).viewModel.saveFDOtherData(
            data,
            PreferenceManager(activity as NiveshFdMainActivity).getToken(),
            activity as NiveshFdMainActivity
        )
        (activity as NiveshFdMainActivity).viewModel.getFDOtherMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            when (response) {
                is Resource.Success -> {
                    Log.e("saveFDOtherData", " response -->${response.data.toString()}")
                    val saveFDOtherDataResponse: SaveFDOtherDataResponse =
                        Gson().fromJson(
                            response.data?.toString(),
                            SaveFDOtherDataResponse::class.java
                        )
                    saveFDOtherDataResponse.Response.StatusCode.let { code ->
                        when (code) {
                            200 -> {
                                (activity as NiveshFdMainActivity).stepFourApi(payUrl, value)
                            }
                            //  650 -> refreshToken()
                            else -> {
                                if (saveFDOtherDataResponse.Response.Errors.isNotEmpty()) {
                                    showDialogValidation(
                                        activity as NiveshFdMainActivity,
                                        saveFDOtherDataResponse.Response.Errors[0].ErrorMessage
                                    )
                                } else {
                                    showDialogValidation(
                                        activity as NiveshFdMainActivity,
                                        "".plus(saveFDOtherDataResponse.Response.Message)
                                    )
                                }
                            }
                        }
                    }
                }

                is Resource.Error -> {
                    response.message?.let { message ->
                        showDialogValidation(activity as NiveshFdMainActivity, message)
                    }
                }
                is Resource.Loading -> {
                    //   ProgressUtil.hideLoading()
                }
                is Resource.DataError -> {

                }
            }
        }
    }

    private fun setUpRecyclerView(getCustomerList: MutableList<GetCodes>) {
        binding.rvTerms.layoutManager =
            LinearLayoutManager(activity as NiveshFdMainActivity)
        val customerListAdapter = CustomerListAdapter(getCustomerList)
        binding.rvTerms.adapter = customerListAdapter

    }

    fun displayReceivedData() {
        getFDDetailsApi()
    }

    private fun getFDDetailsApi() {
        if (Common.isNetworkAvailable(activity as NiveshFdMainActivity)) {
            val getFDDetailsRequest = GetFDDetailsRequest()
            getFDDetailsRequest.FDProvider = getString(R.string.bajaj)
            getFDDetailsRequest.NiveshClientCode =
                (activity as NiveshFdMainActivity).getClientDetailsResponse.ObjectResponse?.clientDetails?.clientMasterMFD?.CLIENT_CODE
            getFDDetailsRequest.UniqueId = (activity as NiveshFdMainActivity).uniqueId
            (activity as NiveshFdMainActivity).viewModel.getFDDetails(
                getFDDetailsRequest,
                PreferenceManager(activity as NiveshFdMainActivity).getToken(),
                activity as NiveshFdMainActivity
            )
            (activity as NiveshFdMainActivity).viewModel.getFDDetailsMutableData.observe(
                viewLifecycleOwner
            ) { response ->
                when (response) {
                    is Resource.Success -> {
                        Log.e("getFDDetailsApi", " response -->${response.data.toString()}")
                        val getFDDetailsResponse: GetFDDetailsResponse =
                            Gson().fromJson(
                                response.data?.toString(),
                                GetFDDetailsResponse::class.java
                            )
                        getFDDetailsResponse.Response.StatusCode.let { code ->
                            when (code) {
                                200 -> {
                                    binding.tvInvestedAmount.text =
                                        getString(R.string.rs).plus(getFDDetailsResponse.Response.FDDataResponse.FDAmount.toString())
                                    binding.tvTenure.text =
                                        getFDDetailsResponse.Response.FDDataResponse.Tenure.toString()
                                            .plus(" Months")
                                    binding.tvInterestPayout.text =
                                        getFDDetailsResponse.Response.FDDataResponse.Frequency
                                    binding.tvRateOfInterest.text =
                                        getFDDetailsResponse.Response.FDDataResponse.RateOfInterest.toString()
                                            .plus(" % p.a.")
                                    payUrl = getFDDetailsResponse.Response.FDDataResponse.PaymentUrl
                                    value = getFDDetailsResponse.Response.FDDataResponse.Value
                                }
                                //  650 -> refreshToken()
                                else -> {
                                    if (getFDDetailsResponse.Response.Errors.isNotEmpty()) {
                                        showDialogValidation(
                                            activity as NiveshFdMainActivity,
                                            getFDDetailsResponse.Response.Errors[0].ErrorMessage
                                        )
                                    } else {
                                        showDialogValidation(
                                            activity as NiveshFdMainActivity,
                                            "".plus(getFDDetailsResponse.Response.Message)
                                        )
                                    }
                                }
                            }
                        }
                    }

                    is Resource.Error -> {
                        response.message?.let { message ->
                            showDialogValidation(activity as NiveshFdMainActivity, message)
                        }
                    }
                    is Resource.Loading -> {

                    }
                    is Resource.DataError -> {

                    }
                }
            }

        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}