package com.pan_american.android.ui.resource_management.hotel_resource

import android.os.Bundle
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.resource_management.hotel_resource.entity.UpdateHotelResource
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceDetailRequest
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceDetailResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddHotelResourceBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddHotelResourceActivity : BaseActivity<ActivityAddHotelResourceBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var hotelResourceId = 0

    val apiService = ServiceCreator.create<APIService>()

    private val updateHotelResource = UpdateHotelResource()

    private var isChose = false

    private var fromList = false

    override fun getViewBinding() = ActivityAddHotelResourceBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        screenAdaptation(binding)

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            hotelResourceId = getIntExtra("id", 0)
        }

        initTitle()
        initViews()
        initEvents()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            if (fromList) {
                titleText.text = resources.getString(R.string.hotel_resource_detail)
            } else {
                titleText.text = resources.getString(R.string.add_hotel_resource)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {

        if (fromList) {

            getHotelDataDetailById()

            binding.commit.setText(resources.getString(R.string.update))

            if (!OASystem.authorization(OASystem.HOTEL_RESOURCE, OASystem.EDIT)) {
                binding.apply {
                    hotelName.isEnabled = false
                    hotelLocation.isEnabled = false
                    hotelAddress.isEnabled(false)
                    hotelPhone.isEnabled = false
                    hotelFax.isEnabled = false
                    hotelLevel.isEnabled = false
                    contactsName.isEnabled = false
                    contactsPhone.isEnabled = false
                    otherInfo.isEnabled(false)

                    commit.setText(resources.getString(R.string.back))
                }
            }

        } else {
            binding.commit.setText(resources.getString(R.string.add))
        }
    }

    override fun initEvents() {

        binding.hotelLevel.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<String>().setData(OASystem.level)
                    .setLayoutId(R.layout.item_selector).addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data

                            if (binding.hotelLevel.text == data) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<String> {
                        override fun onItemClick(position: Int) {

                            binding.hotelLevel.text = OASystem.level[position]
                            isChose = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            if (fromList) {
                if (!OASystem.authorization(OASystem.HOTEL_RESOURCE, OASystem.EDIT)) {
                    back()
                    return@setOnClickListener
                }
            }

            when {
                binding.hotelName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_name_input_hint))
                }

                binding.hotelLocation.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_located_input_hint))
                }

                binding.hotelAddress.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.hotel_address_input_hint))
                }

                binding.hotelPhone.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_tel_input_hint))
                }

                !isChose -> {
                    showMessage(resources.getString(R.string.hotel_level_select_hint))
                }

                binding.contactsName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.connector_name_input_hint))
                }

                binding.contactsPhone.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.contacts_tel_hint))
                }

                else -> {
                    binding.commit.setButtonStatus(1)

                    if (fromList) {
                        initHotelResource(2)
                        updateHotelResourceInfo()
                    } else {
                        if (isChose) {
                            initHotelResource(1)
                            updateHotelResourceInfo()
                        } else {
                            showMessage(resources.getString(R.string.hotel_level_select_hint))
                        }
                    }
                }
            }
        }
    }

    private fun getHotelDataDetailById() {

        apiService.getHotelResourceDetail(HotelResourceDetailRequest(hotelResourceId)).enqueue(object : Callback<HotelResourceDetailResponse> {
            override fun onResponse(
                call: Call<HotelResourceDetailResponse>,
                response: Response<HotelResourceDetailResponse>
            ) {
                val detailResponse = response.body()

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

                        binding.apply {
                            hotelName.setText(hotelResourceDetail.name)
                            hotelLocation.setText(hotelResourceDetail.city)
                            hotelAddress.setText(hotelResourceDetail.address)
                            hotelPhone.setText(hotelResourceDetail.tel)
                            hotelFax.setText(hotelResourceDetail.fax)

                            for (item in OASystem.level) {
                                if (item == hotelResourceDetail.level) {
                                    hotelLevel.text = hotelResourceDetail.level
                                    isChose = true
                                }
                            }

                            contactsName.setText(hotelResourceDetail.contact)
                            contactsPhone.setText(hotelResourceDetail.contactPhone)
                            otherInfo.setText(hotelResourceDetail.otherInformation)
                        }
                    }
                }
            }

            override fun onFailure(call: Call<HotelResourceDetailResponse>, t: Throwable) {
                showErrorInfo(R.string.hotel_resource_detail_get_failed)
            }
        })
    }

    private fun initHotelResource(type: Int) {
        updateHotelResource.apply {
            id = hotelResourceId
            name = binding.hotelName.text.toString()
            city = binding.hotelLocation.text.toString()
            address = binding.hotelAddress.getText()
            tel = binding.hotelPhone.text.toString()
            fax = binding.hotelFax.text.toString()
            level = binding.hotelLevel.text.toString()
            contact = binding.contactsName.text.toString()
            contactPhone = binding.contactsPhone.text.toString()
            otherInformation = binding.otherInfo.getText()

            status = type
        }
    }

    private fun updateHotelResourceInfo() {

        apiService.hotelDataOperation(updateHotelResource).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val baseResponse = response.body()
                if (baseResponse != null) {
                    if (baseResponse.code == 200) {
                        if (updateHotelResource.status == 1) {
                            showMessage(resources.getString(R.string.insert_success))
                        } else {
                            showMessage(resources.getString(R.string.update_success))
                        }

                        OASystem.needRefresh = true

                        back()

                    } else {
                        showMessage(baseResponse.msg)

                        binding.commit.setButtonStatus(0)
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                binding.commit.setButtonStatus(0)

                showErrorInfo(R.string.update_error)
            }
        })
    }
}