package com.pan_american.android.ui.financial_module.collection_bill

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillGroupListRequest
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillGroupListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentCollectionBillGroupListBinding
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 CollectionBillGroupListFragment : BaseFragment<FragmentCollectionBillGroupListBinding>() {

    private val collectionBillGroupListRequest = CollectionBillGroupListRequest()

    private val groupNameList = ArrayList<Selector>()

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

    private var totalPage = 0

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

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

        collectionBillGroupListRequest.apply {
            pageIndex = 1
            pageSize = 20
        }

        initViews()

        initEvents()
    }

    override fun initViews() {

        binding.groupInfoContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.groupInfoContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        getGroupList(1)
    }

    override fun initEvents() {

        binding.searchText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                collectionBillGroupListRequest.pageIndex = 1
                collectionBillGroupListRequest.searchValue = binding.searchText.text.toString()
                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupNameList.size)
                groupNameList.clear()
                getGroupList(2)
            }
        })
    }

    private fun getGroupList(type: Int) {

        apiService.getCollectionBillGroupList(collectionBillGroupListRequest).enqueue(object : Callback<CollectionBillGroupListResponse> {
            override fun onResponse(
                call: Call<CollectionBillGroupListResponse>,
                response: Response<CollectionBillGroupListResponse>
            ) {
                val listResponse = response.body()

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

                        listResponse.data.apply {

                            if (groupNameData.size == 0) {
                                showMessage(resources.getString(R.string.no_data))
                            } else {
                                for (item in groupNameData) {
                                    groupNameList.add(item)
                                }
                            }

                            when (type) {
                                1 -> {
                                    totalPage = groupTotalPage
                                    binding.groupInfoContainer.setEnableLoadMore(totalPage > collectionBillGroupListRequest.pageIndex)
                                    initList()
                                }

                                2 -> {
                                    binding.groupInfoContainer.finishRefresh()
                                    totalPage = groupTotalPage
                                    binding.groupInfoContainer.setEnableLoadMore(totalPage > collectionBillGroupListRequest.pageIndex)
                                    initList()
                                }

                                3 -> {
                                    binding.groupInfoContainer.finishLoadMore()
                                    binding.groupInfoContainer.setEnableLoadMore(collectionBillGroupListRequest.pageIndex < totalPage)
                                    binding.groupInfoList.adapter!!.notifyItemInserted(
                                        groupNameList.size
                                    )
                                }
                            }
                        }
                    } else {
                        showMessage(listResponse.msg)
                    }
                }
            }

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

    private fun initList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.groupInfoList.layoutManager = layoutManager

        val adapter = ListAdapter.Builder<Selector>().apply {
            setLayoutId(R.layout.item_group_name_list)
            setData(groupNameList)
            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) {
                groupNameList[position].apply {

                    val intent = Intent(OASystem.context, CollectionBillPaymentListActivity::class.java).apply {
                        putExtra("groupId", id)
                    }

                    startActivity(intent)
                }
            }
        }

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

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