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

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
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.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitGroupListRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitGroupListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityEntryAndExitGroupListBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class EntryAndExitFeeGroupListActivity : BaseActivity<ActivityEntryAndExitGroupListBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private val entryAndExitGroupListRequest = EntryAndExitGroupListRequest().apply {
        pageIndex = 1
        pageSize = 20
    }

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

    private val groupNameList = ArrayList<Selector>()

    private var totalPage = 0

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

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

        initTitle()

        initViews()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.entry_and_exit_fee_detail)

            searchView.visibility = View.VISIBLE

            searchText.addTextChangedListener {
                entryAndExitGroupListRequest.apply {
                    pageIndex = 1
                    groupName = searchText.text.toString()
                }

                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupNameList.size)
                groupNameList.clear()
                getGroupList(2)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        binding.groupInfoContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.groupInfoContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        getGroupList(1)
    }

    private fun getGroupList(type: Int) {
        apiService.getEntryAndExitGroupList(entryAndExitGroupListRequest).enqueue(object :
            Callback<EntryAndExitGroupListResponse> {
            override fun onResponse(
                call: Call<EntryAndExitGroupListResponse>,
                response: Response<EntryAndExitGroupListResponse>
            ) {
                val listResponse = response.body()

                if (listResponse != null) {
                    if (listResponse.code == 200) {
                        if (listResponse.data.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                        } else {

                            for (item in listResponse.data) {
                                groupNameList.add(item)
                            }

                            when(type) {

                                1 -> {
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupInfoContainer.setEnableLoadMore(totalPage > entryAndExitGroupListRequest.pageIndex)
                                    initList()
                                }

                                2 -> {
                                    binding.groupInfoContainer.finishRefresh()
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupInfoContainer.setEnableLoadMore(entryAndExitGroupListRequest.pageIndex < totalPage)
                                    initList()
                                }

                                3 -> {
                                    binding.groupInfoContainer.finishLoadMore()
                                    binding.groupInfoContainer.setEnableLoadMore(entryAndExitGroupListRequest.pageIndex < totalPage)
                                    binding.groupInfoList.adapter!!.notifyItemInserted(groupNameList.size)
                                }
                            }
                        }

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

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

    private fun getTotalPage(count: Int): Int {
        var totalPage = count / 20
        if (count % 20 != 0) {
            totalPage++
        }

        return totalPage
    }

    private fun initList() {
        if (groupNameList.size == 0) {
            return
        }

        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.groupInfoList.layoutManager = layoutManager

        val adapter = ListAdapter.Builder<Selector>().apply {
            setData(groupNameList)
            setLayoutId(R.layout.item_group_name_list)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.selector_item_name).text = data.groupName
            }
        }.create()

        binding.groupInfoList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
            override fun onItemClick(position: Int) {
                val intent = Intent(OASystem.context, EntryAndExitDetailActivity::class.java).apply {
                    putExtra("groupId", groupNameList[position].id)
                }
                startActivity(intent)
            }
        }

        binding.groupInfoContainer.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                entryAndExitGroupListRequest.pageIndex = 1
                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupNameList.size)
                groupNameList.clear()
                getGroupList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (entryAndExitGroupListRequest.pageIndex < totalPage) {
                    entryAndExitGroupListRequest.pageIndex += 1
                    getGroupList(3)
                }
            }
        })
    }
}