package com.cocking.fight.screen.dialogfragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sambath.klaklouk_main.screen.main.cflive.statement.report.ReportAdapter
import com.sambath.klaklouk_main.screen.main.cflive.statement.report.Type
import com.sambath.klaklouk_main.R
import com.sambath.klaklouk_main.app.App
import com.sambath.klaklouk_main.app.getErrorCode
import com.sambath.klaklouk_main.remote.ReportBody
import com.sambath.klaklouk_main.remote.ReportOne
import com.sambath.klaklouk_main.remote.ReportTwo
import com.sambath.klaklouk_main.remote.User
import com.sambath.klaklouk_main.util.Const
import com.sambath.klaklouk_main.util.ModelPreferencesManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.app_bar_dialog.*
import kotlinx.android.synthetic.main.fragment_dialog_report.*
import java.text.DecimalFormat
import java.util.concurrent.TimeUnit

class StatementDialogFragment : DialogFragment() {
    private lateinit var adapterTb1: ReportAdapter
    private lateinit var adapterTb2: ReportAdapter
    private lateinit var adapterTb3: ReportAdapter
    private lateinit var rvTab1: RecyclerView
    private lateinit var rvTab2: RecyclerView
    private lateinit var rvTab3: RecyclerView
    private lateinit var user: User
    private lateinit var layoutManager1: LinearLayoutManager
    private lateinit var layoutManager2: LinearLayoutManager
    private var pageOne: Int = 1
    private var totalPageOne: Int = 1
    private var totalRecordOne: Int = 0
    private var isLoadingOne: Boolean = false
    private var pageTwo: Int = 1
    private var totalPageTwo: Int = 1
    private var totalRecordTwo: Int = 0
    private var isLoadingTwo: Boolean = false
    private var listOne: List<ReportOne> = arrayListOf()
    private var listTwo: List<ReportTwo> = arrayListOf()
    private val apiService = App.injectApiService()
    private lateinit var statementDialogViewModel: StatementDialogViewModel
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        user = ModelPreferencesManager.getUser(Const.USER_KEY)!!
        statementDialogViewModel =
            StatementDialogViewModel(App.injectApiService(), App.injectPrefHelper())
        return inflater.inflate(R.layout.fragment_dialog_report, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        txtUserId.text = user.userName
        txtSubRed.text = currencyFormat(user.accountBalances.toString())
        img_back.setOnClickListener {
            dismiss()
        }
        rvTab1 = view.findViewById(R.id.rv_tb1)
        rvTab2 = view.findViewById(R.id.rv_tb2)
        rvTab3 = view.findViewById(R.id.rv_tb3)
        v_tab1.setOnClickListener {
            bg_select_tab1.visibility = View.VISIBLE
            bg_select_tab2.visibility = View.INVISIBLE
            bg_select_tab3.visibility = View.INVISIBLE
            rvTab1.visibility = View.VISIBLE
            rvTab2.visibility = View.INVISIBLE
            tab3.visibility = View.INVISIBLE
        }
        v_tab2.setOnClickListener {
            bg_select_tab1.visibility = View.INVISIBLE
            bg_select_tab2.visibility = View.VISIBLE
            bg_select_tab3.visibility = View.INVISIBLE
            rvTab1.visibility = View.INVISIBLE
            rvTab2.visibility = View.VISIBLE
            tab3.visibility = View.INVISIBLE
        }
        v_tab3.setOnClickListener {
            bg_select_tab1.visibility = View.INVISIBLE
            bg_select_tab2.visibility = View.INVISIBLE
            bg_select_tab3.visibility = View.VISIBLE
            rvTab1.visibility = View.INVISIBLE
            rvTab2.visibility = View.INVISIBLE
            tab3.visibility = View.VISIBLE
        }
        img_back.setOnClickListener {
            dialog?.dismiss()
        }
        init()
//        getDataOne()
//        getDataTwo()
        exOne(ReportBody(20, 1, "2021-12-17", "2021-12-31"))
        exTwo(ReportBody(20, 1, "2021-12-17", "2021-12-31"))
//        statementDialogViewModel.getReportTwo(1)
        statementDialogViewModel.getReportThree()
//        statementDialogViewModel.stateOne.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
//            getReportOne(it)
//        })
//        statementDialogViewModel.stateTwo.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
//            getReportTwo(it)
//        })
        statementDialogViewModel.stateThree.observe(
            viewLifecycleOwner,
            androidx.lifecycle.Observer {
                getReportThree(it)
            })
        rvTab1.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                val visibleItemCount: Int = layoutManager1.childCount
//                val pastVisibleItem: Int = layoutManager1.findFirstCompletelyVisibleItemPosition()
                val total: Int = adapterTb1.itemCount
                if (!isLoadingOne) {
                    if (total < totalRecordOne) {
//                        getDataOne()
                        Log.d("getReport", "itemCount1 :: " + total)
                        exOne(ReportBody(20, 1, "2021-12-17", "2021-12-31"))
                    }
                }
                super.onScrolled(recyclerView, dx, dy)
            }
        })
        rvTab2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val visibleItemCount: Int = layoutManager2.childCount
                val pastVisibleItem: Int = layoutManager2.findFirstCompletelyVisibleItemPosition()
                val total: Int = adapterTb2.itemCount
                if (!isLoadingTwo) {
                    Log.d("getReport", "total :: plus " + total + " :: " + totalRecordTwo)
                    if (total < totalRecordTwo) {
//                        getDataTwo()
                        Log.d("getReport", "itemCount2 :: " + total)
                        exTwo(ReportBody(20, 1, "2021-12-17", "2021-12-31"))
                    }
                }
                super.onScrolled(recyclerView, dx, dy)
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme);
    }

//    private fun getDataOne() {
//        statementDialogViewModel.getReportOne(pageOne)
//        pageOne++
//    }

//    private fun getDataTwo() {
//        isLoadingTwo = true
//        statementDialogViewModel.getReportTwo(pageTwo)
//        pageTwo++
//    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
    }

    companion object {
        const val TAG = "PurchaseConfirmationDialog"
    }

//    private fun getReportOne(data: StatementDialogViewState) {
//        progress.isVisible = false
//        if (data.reportOneList != null) {
//            totalPageOne = data.totalPageOne
//            Log.d("getReport", "1 :: " + data.reportOneList!!.size)
//            adapterTb1.submitList(data.reportOneList)
//        }
//    }

//    private fun getReportTwo(data: StatementDialogViewState) {
//        if (data.reportTwoList.isNullOrEmpty()) {
//            Log.d("getReport", "2 :: " + data.reportTwoList!!.size)
//            totalPageTwo = data.totalPageTwo
//            val li: List<ReportTwo> = data.reportTwoList!!
//            listTwo = concatenate(listTwo, li)
//            adapterTb2.submitList(listTwo)
//            isLoadingTwo = false
//        }
//    }

    private fun getReportThree(data: StatementDialogViewState) {
        if (data.reportThreeList != null) {
            Log.d("getReport", "3 :: " + data.reportThreeList!!.size)
            adapterTb3.submitList(data.reportThreeList)
        }
    }

    private fun exOne(reportBetting: ReportBody) {
        isLoadingOne = true
        pageOne++
        val disposables = CompositeDisposable()
        disposables.add(
            apiService.getReportOne(reportBetting)
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
                        progress.isVisible = false
                        totalPageOne = it.data.totalPages
                        totalRecordOne = it.data.totalRows
                        val li: List<ReportOne> = it.data.reports
                        listOne = concatenate(listOne, li)
                        Log.d("getReport", "listOne :: " + listOne.size)
                        adapterTb1.submitList(listOne)
                        isLoadingOne = false
                    } else {
                        isLoadingOne = false
                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.message.description
                    }
                }, {
                    isLoadingOne = false
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.getErrorCode()
                })
        )
    }

    private fun exTwo(reportBetting: ReportBody) {
        isLoadingTwo = true
        pageTwo++
        Log.d("getReport", "page2 :: " + reportBetting.page)
        val disposables = CompositeDisposable()
        disposables.add(
            apiService.getReportTwo(reportBetting)
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
                        totalPageTwo = it.data.totalPages
                        totalRecordTwo = it.data.totalRows
                        val li: List<ReportTwo> = it.data.results
                        listTwo = concatenate(listTwo, li)
                        Log.d("getReport", "listTwo :: " + listTwo.size)
                        adapterTb2.submitList(listTwo)
                        isLoadingTwo = false
                    } else {
                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.message.description
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.getErrorCode()
                })
        )
    }

    fun init() {
//        progress.isVisible = state.isProgress
//        if (!state.winList.isNullOrEmpty()) {
        adapterTb1 = ReportAdapter(Type.WIN)
//            adapterTb1.submitList(state.winList)
        rvTab1.setHasFixedSize(true)
        layoutManager1 = LinearLayoutManager(context)
        rvTab1.layoutManager = layoutManager1
        rvTab1.adapter = adapterTb1
//        }
//        if (!state.winLostList.isNullOrEmpty()) {
        adapterTb2 = ReportAdapter(Type.WIN_LOST)
//            adapterTb2.submitList(state.winLostList)
        rvTab2.setHasFixedSize(true)
        layoutManager2 = LinearLayoutManager(context)
        rvTab2.layoutManager = layoutManager2
        rvTab2.adapter = adapterTb2
//        }
//        if (!state.statementList.isNullOrEmpty()) {
        adapterTb3 = ReportAdapter(Type.STATEMENT)
//            adapterTb3.submitList(state.statementList)
        rvTab3.setHasFixedSize(true)
        rvTab3.layoutManager = LinearLayoutManager(context)
        rvTab3.adapter = adapterTb3
//        }
    }

    fun currencyFormat(amount: Double): String? {
        val formatter = DecimalFormat("#,###")
        return formatter.format(amount)
    }

    private fun currencyFormat(amount: String): String? {
        val formatter = DecimalFormat("#,###")
        return formatter.format(amount)
    }

    private fun <T> concatenate(vararg lists: List<T>): List<T> {
        return listOf(*lists).flatten()
    }
}