package com.pan_american.android.ui.group_visa.visa_payment_insert

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
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.BaseResponse
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.group_visa.visa_payment_insert.entity.VisaPaymentListItem
import com.pan_american.android.data.model.group_visa.visa_payment_insert.network.VisaPaymentListRequest
import com.pan_american.android.data.model.group_visa.visa_payment_insert.network.VisaPaymentListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentVisaPaymentListBinding
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 VisaPaymentListFragment : BaseFragment<FragmentVisaPaymentListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

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

    private lateinit var visaPaymentListRequest: VisaPaymentListRequest

    private var listInit = false

    private var pageIndex = 1

    private var totalPage = 0

    private var visaPaymentList = ArrayList<VisaPaymentListItem>()

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

    override fun onStart() {
        super.onStart()

        requireArguments().apply {
            groupId = getInt("groupId")
            binding.groupName.text = getString("teamName")
            tourCode = getString("tourCode", "")
            binding.groupCustomer.text = getString("clientName")
            binding.visitCountry.text = getString("visitCountry")
            binding.visitDays.text = getString("visitDays")
            binding.visitMembers.text = getString("visitPNumber")
            binding.duringTime.text = getString("duringTime")
        }

        initViews()
        initEvents()
    }

    override fun initViews() {

        if (OASystem.authorization(OASystem.VISA_PAYMENT_INSERT, OASystem.ADD)) {
            binding.addPaymentItem.apply {

                visibility = View.VISIBLE

                binding.addPaymentItem.setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddVisaPaymentActivity::class.java).apply {
                            putExtra("groupId", groupId)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)
                        }
                    startActivity(intent)
                }
            }
        }

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

        visaPaymentListRequest = VisaPaymentListRequest(groupId)

        visaPaymentListRequest.pageIndex = pageIndex

        visaPaymentListRequest.pageSize = 10

        getVisaPaymentList(1)
    }

    override fun initEvents() {

        binding.baseInfoSwitch.setOnClickListener {
            if (isShow) {
                binding.groupBaseInfo.visibility = View.GONE
                binding.baseInfoSwitch.text = resources.getString(R.string.show)
                isShow = false
            } else {
                binding.groupBaseInfo.visibility = View.VISIBLE
                binding.baseInfoSwitch.text = resources.getString(R.string.hide)
                isShow = true
            }
        }
    }

    private fun getVisaPaymentList(type: Int) {
        if (!listInit) {
            apiService.getVisaPaymentListById(visaPaymentListRequest)
                .enqueue(object : Callback<VisaPaymentListResponse> {
                    override fun onResponse(
                        call: Call<VisaPaymentListResponse>,
                        response: Response<VisaPaymentListResponse>
                    ) {
                        val visaListResponse = response.body()

                        if (visaListResponse != null) {
                            if (visaListResponse.code == 200) {
                                for (item in visaListResponse.data.dataList) {
                                    visaPaymentList.add(item)
                                }

                                if (visaPaymentList.size == 0) {
                                    showMessage(resources.getString(R.string.no_data))
                                }

                                when (type) {
                                    1 -> {
                                        totalPage = getTotalPage(
                                            visaListResponse.data.dataCount,
                                            visaListResponse.data.currPageSize
                                        )
                                        binding.visaPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        initList()
                                        listInit = true
                                    }

                                    2 -> {
                                        binding.visaPaymentContainer.finishRefresh()
                                        totalPage = getTotalPage(
                                            visaListResponse.data.dataCount,
                                            visaListResponse.data.currPageSize
                                        )
                                        binding.visaPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        initList()
                                        listInit = true
                                    }

                                    3 -> {
                                        binding.visaPaymentContainer.finishLoadMore()
                                        binding.visaPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        binding.visaPaymentList.adapter!!.notifyItemInserted(
                                            visaPaymentList.size
                                        )
                                        listInit = true
                                    }
                                }

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

                    override fun onFailure(call: Call<VisaPaymentListResponse>, t: Throwable) {
                        showErrorInfo(R.string.visa_payment_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                visaPaymentListRequest.pageIndex = pageIndex
                visaPaymentList.clear()
                listInit = false
                getVisaPaymentList(2)
            }
        }
    }

    private fun getTotalPage(dataCount: Int, pageSize: Int): Int {
        var totalPage = dataCount / pageSize
        if (dataCount % pageSize != 0) {
            totalPage++
        }

        return totalPage
    }

    private fun initList() {

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

        val adapter = CardAdapter.Builder<VisaPaymentListItem>().apply {
            setLayoutId(R.layout.item_visa_payment)
            setData(visaPaymentList)
            setCanDelete(OASystem.authorization(OASystem.VISA_PAYMENT_INSERT, OASystem.DELETE))
            addBindView { itemView, data ->

                if (data.visaDescription.isBlank()) {
                    val clientList = data.visaClient.trim().split("[*TuT*]")

                    if (clientList.size == 1) {
                        itemView.findViewById<TextView>(R.id.visa_client).text = clientList[0]
                    } else {
                        itemView.findViewById<TextView>(R.id.visa_client).text = String.format(
                            resources.getString(R.string.client_list_title_format),
                            clientList[0],
                            clientList.size
                        )
                    }
                } else {
                    itemView.findViewById<TextView>(R.id.visa_client).text = data.visaDescription
                }

                itemView.findViewById<TextView>(R.id.visa_price).text = String.format(
                    resources.getString(R.string.currency_name_code_format),
                    data.visaPrice.toString(),
                    data.visaCurrencyStr
                )
                itemView.findViewById<TextView>(R.id.visa_number).text = data.visaNumber.toString()
                itemView.findViewById<TextView>(R.id.visa_free_number).text =
                    data.visaFreeNumber.toString()

                when (data.isThird) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.is_third).text =
                            resources.getString(R.string.no)
                    }

                    1 -> {
                        itemView.findViewById<TextView>(R.id.is_third).text =
                            resources.getString(R.string.yes)
                    }
                }

                when (data.isAuditGM) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_wait)
                            setTextColor(Color.rgb(23, 171, 227))
                        }
                    }

                    1 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_passed)
                            setTextColor(Color.rgb(84, 213, 77))
                        }
                    }

                    2 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_reject)
                            setTextColor(Color.rgb(210, 45, 34))
                        }
                    }

                    3 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).text =
                            resources.getString(R.string.auto_verify)
                    }
                }
            }
        }.create()

        binding.visaPaymentList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<VisaPaymentListItem> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddVisaPaymentActivity::class.java).apply {
                            putExtra("fromList", true)
                            putExtra("groupId", groupId)
                            putExtra("paymentId", visaPaymentList[position].id)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)

                            putExtra("paymentCurrency", visaPaymentList[position].visaCurrencyStr)

                            putExtra("isAuditGM", visaPaymentList[position].isAuditGM)
                        }
                    startActivity(intent)
                }

                override fun onItemDelete(position: Int) {
                    CustomAlertDialog.Builder(OASystem.context).apply {
                        setTitle(resources.getString(R.string.alert))
                        setMessage(
                            String.format(
                                resources.getString(R.string.delete_alert_text),
                                visaPaymentList[position].visaClient
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteVisaPaymentItem(position)
                        }
                    }.show()
                }
            }

        binding.visaPaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                visaPaymentListRequest.pageIndex = pageIndex
                visaPaymentList.clear()
                listInit = false
                getVisaPaymentList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    visaPaymentListRequest.pageIndex = pageIndex
                    listInit = false
                    getVisaPaymentList(3)
                }
            }
        })
    }

    private fun deleteVisaPaymentItem(position: Int) {
        apiService.deleteVisaPayment(DeleteRequest(visaPaymentList[position].id))
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {
                    val deleteResponse = response.body()

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

                            visaPaymentList.removeAt(position)
                            binding.visaPaymentList.adapter!!.notifyItemRemoved(position)
                            binding.visaPaymentList.adapter!!.notifyItemRangeRemoved(
                                position, visaPaymentList.size - position
                            )

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

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

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