package com.pan_american.android.ui.financial_module.accounts_receivable_report

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.adapter.AccountsReceivableReportAdapter
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.entity.AccountReceivableReportFeeItem
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.entity.AccountReceivableReportListItem
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.network.AccountReceivableReportListRequest
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.network.AccountReceivableReportListResponse
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.network.GenerateAccountReceivableReportResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAccountsReceivableReportBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AccountsReceivableReportActivity : BaseActivity<ActivityAccountsReceivableReportBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

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

    private var accountReceivableReportListRequest = AccountReceivableReportListRequest()

    private var isFilterShown = true

    private val accountReceivableReportList = ArrayList<AccountReceivableReportListItem>()

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

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

        screenAdaptation(binding)

        initTitle()

        initViews()

        initEvents()
    }

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

            rightTextField.text = resources.getString(R.string.generate)

            rightTextField.setOnClickListener {
                accountReceivableReportListRequest.requestType = 2

                generateReport()
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        binding.commit.setText(resources.getString(R.string.search))
    }

    override fun initEvents() {

        binding.filterSwitch.setOnClickListener {
            if (isFilterShown) {
                binding.dateFilter.visibility = View.GONE
                binding.filterSwitch.text = resources.getString(R.string.show)
                isFilterShown = false
            } else {
                binding.dateFilter.visibility = View.VISIBLE
                binding.filterSwitch.text = resources.getString(R.string.hide)
                isFilterShown = true
            }
        }

        binding.startDate.setOnClickListener {
            showDatePicker(resources.getString(R.string.start_date), binding.startDate)
        }

        binding.endDate.setOnClickListener {
            showDatePicker(resources.getString(R.string.end_date), binding.endDate)
        }

        binding.commit.setOnClickListener {
            if (binding.startDate.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.start_date_select_hint))
                return@setOnClickListener
            }

            if (binding.endDate.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.end_date_select_hint))
                return@setOnClickListener
            }

            val inputMethodManager =
                this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (inputMethodManager.isActive) {
                inputMethodManager.hideSoftInputFromWindow(
                    this.window.decorView.windowToken, 0
                )
            }

            accountReceivableReportListRequest.apply {
                startDate = binding.startDate.text.toString()
                endDate = binding.endDate.text.toString()
                groupName = binding.groupName.text.toString()
                requestType = 1
            }

            if (accountReceivableReportList.size > 0) {
                accountReceivableReportList.clear()
            }

            getAccountsReceivableReportGroupList()
        }
    }

    private fun getAccountsReceivableReportGroupList() {
        apiService.getAccountReceivableReportList(accountReceivableReportListRequest)
            .enqueue(object : Callback<AccountReceivableReportListResponse> {
                override fun onResponse(
                    call: Call<AccountReceivableReportListResponse>,
                    response: Response<AccountReceivableReportListResponse>
                ) {
                    val listResponse = response.body()

                    if (listResponse != null) {
                        if (listResponse.code == 200) {
                            if (listResponse.data.dataList.size > 0) {
                                for (item in listResponse.data.dataList) {
                                    accountReceivableReportList.add(item)
                                }

                                binding.receivablesReportTotal.visibility = View.VISIBLE

                                binding.receivablesReportTotal.text = String.format(
                                    resources.getString(R.string.accounts_receivable_report_total),
                                    listResponse.data.totalFr,
                                    listResponse.data.totalPr,
                                    listResponse.data.totalBalance
                                )

                                titleBinding.rightTextField.visibility = View.VISIBLE

                            } else {
                                showMessage(resources.getString(R.string.no_data))

                                binding.receivablesReportTotal.visibility = View.GONE

                                titleBinding.rightTextField.visibility = View.GONE
                            }

                            initList()

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

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

    private fun initList() {

        if (accountReceivableReportList.size == 0) {
            return
        }

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

        val adapter = AccountsReceivableReportAdapter(accountReceivableReportList)

        binding.groupReceivableList.adapter = adapter

        adapter.onDetailClick = object : AccountsReceivableReportAdapter.OnRecyclerViewItemClick {
            override fun onDetailClick(position: Int) {
                val detailView = View.inflate(
                    OASystem.context,
                    R.layout.popup_accounts_receivable_report_detail,
                    null
                )
                popupWindow = PopupWindow(
                    detailView,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    binding.root.height * 3 / 4
                )

                showPopupWindow {
                    val paymentDetail =
                        detailView.findViewById<RecyclerView>(R.id.account_receivable_report_detail)
                    val noDataHint = detailView.findViewById<TextView>(R.id.no_data_hint)
                    val receiveDepartment =
                        detailView.findViewById<TextView>(R.id.payment_receive_department)

                    accountReceivableReportList[position].apply {
                        if (feeItem.size == 0) {
                            paymentDetail.visibility = View.GONE
                            noDataHint.visibility = View.VISIBLE
                        } else {

                            paymentDetail.visibility = View.VISIBLE
                            noDataHint.visibility = View.GONE

                            val detailLayoutManager = LinearLayoutManager(OASystem.context)
                            paymentDetail.layoutManager = detailLayoutManager

                            val detailAdapter =
                                ListAdapter.Builder<AccountReceivableReportFeeItem>().apply {
                                    setLayoutId(R.layout.item_accounts_receivable_report_detail)
                                    setData(feeItem)
                                    addBindView { itemView, data ->
                                        itemView.findViewById<TextView>(R.id.name).text =
                                            data.client
                                        if (data.frCurrency.isBlank() or (data.frCurrency == "-")) {
                                            itemView.findViewById<TextView>(R.id.receivables).text =
                                                String.format(
                                                    resources.getString(R.string.currency_name_code_format),
                                                    "0.00",
                                                    "CNY"
                                                )
                                        } else {
                                            itemView.findViewById<TextView>(R.id.receivables).text =
                                                String.format(
                                                    resources.getString(R.string.currency_name_code_format),
                                                    data.frMoney,
                                                    data.frCurrency
                                                )
                                        }

                                        itemView.findViewById<TextView>(R.id.exchange_rate).text =
                                            data.frRate.ifBlank { "-" }
                                        if (data.prCurrency.isBlank() or (data.prCurrency == "-")) {
                                            itemView.findViewById<TextView>(R.id.payment_collected).text =
                                                String.format(
                                                    resources.getString(R.string.currency_name_code_format),
                                                    "0.00",
                                                    "CNY"
                                                )
                                        } else {
                                            itemView.findViewById<TextView>(R.id.payment_collected).text =
                                                String.format(
                                                    resources.getString(R.string.currency_name_code_format),
                                                    data.prMoney,
                                                    data.prCurrency
                                                )
                                        }

                                        itemView.findViewById<TextView>(R.id.payment_balance).text =
                                            data.balPayment.ifBlank { "-" }
                                        itemView.findViewById<TextView>(R.id.payment_way).text =
                                            data.prReceivablesType.ifBlank { "-" }
                                        itemView.findViewById<TextView>(R.id.payment_collected_time).text =
                                            data.prTime.ifBlank { "-" }
                                    }
                                }.create()


                            paymentDetail.adapter = detailAdapter

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

                                }
                            }
                        }

                        receiveDepartment.text =
                            prClient.ifBlank { resources.getString(R.string.no_data) }
                    }

                    popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
                }
            }
        }
    }

    private fun generateReport() {
        apiService.generateAccountReceivableReport(accountReceivableReportListRequest)
            .enqueue(object : Callback<GenerateAccountReceivableReportResponse> {
                override fun onResponse(
                    call: Call<GenerateAccountReceivableReportResponse>,
                    response: Response<GenerateAccountReceivableReportResponse>
                ) {
                    val urlResponse = response.body()

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

                            CustomAlertDialog.Builder().apply {
                                setTitle(resources.getString(R.string.hint))
                                setMessage(
                                    String.format(
                                        resources.getString(R.string.account_receivable_report_generated),
                                        accountReceivableReportListRequest.startDate,
                                        accountReceivableReportListRequest.endDate
                                    )
                                )
                                setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                                    dialog.dismiss()
                                }
                                setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
                                    val uri = Uri.parse(urlResponse.data.url)
                                    startActivity(Intent(Intent.ACTION_VIEW, uri))

                                    dialog.dismiss()
                                }
                            }.show()

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

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