package com.pan_american.android.ui.group_management.entry_and_exit_fee_detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitPaymentTypeRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitTipsRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.InternationalTravelPaymentDetailResponse
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.InternationalTravelTipsResponse
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.UpdateInternationalTravelRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.UpdateInternationalTravelResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentInternationalTravelFeeBinding
import com.pan_american.android.util.MoneyInputFilter
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class InternationalTravelFeeFragment : BaseFragment<FragmentInternationalTravelFeeBinding>() {

    private var groupId = 0

    private var paymentId = 0

    private var economyClassTip = 0.0

    private var businessClassTip = 0.0

    private val apiService = ServiceCreator.create<APIService>()

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentInternationalTravelFeeBinding.inflate(inflater, container, false)

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

        requireArguments().apply {
            groupId = getInt("groupId")
        }

        initViews()

        initEvents()
    }

    override fun initViews() {

        binding.economyClassPrice.filters = arrayOf(MoneyInputFilter(2))
        binding.businessClassPrice.filters = arrayOf(MoneyInputFilter(2))
        binding.firstClassPrice.filters = arrayOf(MoneyInputFilter(2))

        getInternationalTravelFeeDetail()
    }

    private fun getInternationalTravelFeeDetail() {

        if (!isAdded) {
            return
        }

        apiService.getInternationalTravelFeeDetail(
            EntryAndExitPaymentTypeRequest(
                diId = groupId,
                subType = 2
            )
        ).enqueue(object : Callback<InternationalTravelPaymentDetailResponse> {

            override fun onResponse(
                call: Call<InternationalTravelPaymentDetailResponse>,
                response: Response<InternationalTravelPaymentDetailResponse>
            ) {
                val detailResponse = response.body()

                if (detailResponse != null) {
                    if (detailResponse.code == 200) {
                        detailResponse.data.apply {

                            paymentId = id

                            binding.economyClassSelected.isChecked = choiceTwoJJ == 1
                            binding.economyClassPrice.setText(airJJ.toString())

                            binding.businessClassSelected.isChecked = choiceTwoGW == 1
                            binding.businessClassPrice.setText(airGW.toString())

                            binding.firstClassSelected.isChecked = choiceTwoTD == 1
                            binding.firstClassPrice.setText(airTD.toString())

                            binding.cityTrafficPayment.setText(cityTranffic.toString())

                            getInternationalTravelTips()
                        }
                    } else {
                        showMessage(detailResponse.msg)
                    }
                }
            }

            override fun onFailure(
                p0: Call<InternationalTravelPaymentDetailResponse>,
                p1: Throwable
            ) {
                showErrorInfo(R.string.international_travel_payment_get_error)
            }
        })
    }

    private fun getInternationalTravelTips() {

        if (!isAdded) {
            return
        }

        apiService.getInternationalTravelTips(
            EntryAndExitTipsRequest(
                groupId = groupId,
                tipsType = 3
            )
        ).enqueue(object : Callback<InternationalTravelTipsResponse> {
            override fun onResponse(
                call: Call<InternationalTravelTipsResponse>,
                response: Response<InternationalTravelTipsResponse>
            ) {
                val tipsResponse = response.body()

                if (tipsResponse != null) {
                    if (tipsResponse.code == 200) {

                        tipsResponse.data.apply {
                            binding.hint.text = remark

                            economyClassTip = jjcCurrentRate
                            businessClassTip = gwcCurrentRate

                        }

                    } else {
                        showMessage(tipsResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<InternationalTravelTipsResponse>, p1: Throwable) {
                showErrorInfo(R.string.international_travel_tips_get_error)
            }
        })
    }

    override fun initEvents() {

        binding.putIn.setOnClickListener {
            binding.economyClassPrice.setText(economyClassTip.toString())

            binding.businessClassPrice.setText(businessClassTip.toString())
        }

        binding.commit.setOnClickListener {
            if (binding.economyClassPrice.text.isBlank() || binding.economyClassPrice.text.endsWith(
                    '.'
                )
            ) {
                showMessage(resources.getString(R.string.economy_class_price_input_hint))
                return@setOnClickListener
            }

            if (binding.businessClassPrice.text.isBlank() || binding.businessClassPrice.text.endsWith(
                    '.'
                )
            ) {
                showMessage(resources.getString(R.string.business_class_price_input_hint))
                return@setOnClickListener
            }

            if (binding.firstClassPrice.text.isBlank() || binding.firstClassPrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.first_class_price_input_hint))
                return@setOnClickListener
            }

            if (binding.cityTrafficPayment.text.isBlank() || binding.cityTrafficPayment.text.endsWith(
                    '.'
                )
            ) {
                showMessage(resources.getString(R.string.city_traffic_payment_input_hint))
                return@setOnClickListener
            }

            val updateInternationalTravelRequest = UpdateInternationalTravelRequest(
                id = paymentId,
                diId = groupId,
                choiceTwoJJ = if (binding.economyClassSelected.isChecked) {
                    1
                } else {
                    0
                },
                choiceTwoGW = if (binding.businessClassSelected.isChecked) {
                    1
                } else {
                    0
                },
                choiceTwoTD = if (binding.firstClassSelected.isChecked) {
                    1
                } else {
                    0
                },
                airJJ = binding.economyClassPrice.text.toString().toDouble(),
                airGW = binding.businessClassPrice.text.toString().toDouble(),
                airTD = binding.firstClassPrice.text.toString().toDouble(),
                cityTranffic = binding.cityTrafficPayment.text.toString().toDouble()
            )

            updateInternationalTravel(updateInternationalTravelRequest)
        }

    }

    private fun updateInternationalTravel(updateInternationalTravelRequest: UpdateInternationalTravelRequest) {

        if (!isAdded) {
            return
        }

        apiService.updateInternationalTravelPayment(updateInternationalTravelRequest)
            .enqueue(object : Callback<UpdateInternationalTravelResponse> {
                override fun onResponse(
                    call: Call<UpdateInternationalTravelResponse>,
                    response: Response<UpdateInternationalTravelResponse>
                ) {
                    val updateResponse = response.body()

                    if (updateResponse != null) {
                        if (updateResponse.code == 200) {

                            showMessage(resources.getString(R.string.update_success))

                            OASystem.entryAndExitDetailResponse.apply {
                                choiceTwoJJ = updateResponse.data.choiceTwoJJ
                                choiceTwoGW = updateResponse.data.choiceTwoGW
                                choiceTwoTD = updateResponse.data.choiceTwoTD

                                outsideJJPay = updateResponse.data.jjcItemTotal
                                outsideGWPay = updateResponse.data.gwcItemTotal
                                outsideTDPay = updateResponse.data.tdcItemTotal
                            }

                            EventBus.getDefault().post(OASystem.entryAndExitDetailResponse)

                            parentFragmentManager.popBackStack()

                        } else {
                            showMessage(updateResponse.msg)
                        }
                    }
                }

                override fun onFailure(p0: Call<UpdateInternationalTravelResponse>, p1: Throwable) {
                    showErrorInfo(R.string.update_error)
                }
            })
    }
}