package uz.mobiuz.mobiservice.dev.ui.sdk.card

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.coreui.extension.formattedCardNumber
import uz.agr.sdk.coreui.ui.decoration.EndOffsetItemDecoration
import uz.agr.sdk.coreui.ui.decoration.StartOffsetItemDecoration
import uz.agr.sdk.mobi_uz.AGRBilling
import uz.agr.sdk.mobi_uz.BaseListener
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentCardsListBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.network.model.UiStateList
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import javax.inject.Inject

@AndroidEntryPoint
class CardsListFragment : BaseFragment(R.layout.fragment_cards_list) {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: FragmentCardsListBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val viewModel: CardViewModel by viewModels()
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }
    private var phone = ""
    private var selectedCard: CardInfo? = null

    private lateinit var adapter: CardsListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        adapter = CardsListAdapter(false)
        arguments?.let {
            phone = it.getString(CONSTANTS.PHONE) ?: ""
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentCardsListBinding.bind(view)

        viewModel.getAllCards()
        setUpUI()
        collects()


    }

    override fun setUpUI() {

        bn.apply {

            adapter.setOnClickListener { cardInfo, i ->
                onCardClicked(cardInfo)
            }
            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }

            btnAddCard.setOnClickListener {
                navController.navigate(R.id.addCardFragment)
            }

            recyclerView.apply {
                layoutManager = LinearLayoutManager(context)
                setHasFixedSize(true)
                adapter = this@CardsListFragment.adapter
            }
            recyclerView.addItemDecoration(
                StartOffsetItemDecoration(
                    resources.getDimensionPixelOffset(
                        R.dimen.agr_card_list_start_offset
                    )
                )
            )
            recyclerView.addItemDecoration(
                EndOffsetItemDecoration(
                    resources.getDimensionPixelOffset(
                        R.dimen.agr_card_list_end_offset
                    )
                )
            )

//            swipeToRefresh.setColorSchemeResources(
//                R.color.agr_black,
//                R.color.primary100
//            )
//            swipeToRefresh.setOnRefreshListener {
//                MobiUz.refreshCardsInfo(object : BaseListener<List<CardInfo>> {
//                    override fun error(message: String) {
//                        swipeToRefresh.isRefreshing = false
//                        showToastMessage(message)
//                    }
//
//                    override fun loading(boolean: Boolean) {
//                        swipeToRefresh.isRefreshing = boolean
//                    }
//
//                    override fun success(data: List<CardInfo>) {
//                        swipeToRefresh.isRefreshing = false
//                        setData(data)
//                    }
//                })
//            }
        }


    }

    private fun onCardClicked(cardInfo: CardInfo) {
        selectedCard = cardInfo
        showDeleteCardConfirmDialog(cardInfo.pan.formattedCardNumber())
    }

    private fun showDeleteCardConfirmDialog(cardNumber: String) {
        val dialog = MessageDialogFragment(requireContext(), getString(R.string.agr_mobi_uz_delete_card_question))
        dialog.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setCanceledOnTouchOutside(true)
        dialog.setOnCancelClickListener {
            dialog.dismiss()
        }
        dialog.setOnOkClickListener {
            AGRBilling.deleteCard(selectedCard!!, object : BaseListener<Boolean> {
                override fun error(message: String) {}

                override fun loading(boolean: Boolean) {
//                    showProgressDialog(boolean)
                }

                override fun success(data: Boolean) {
                    viewModel.getAllCards()
                }
            })
            dialog.dismiss()
        }
        dialog.show()
    }

    private fun setData(data: List<CardInfo>) {
        bn.recyclerView.isVisible = data.isNotEmpty()
        bn.layoutEmpty.root.isVisible = data.isEmpty()
        adapter.setData(data)
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.cardListUiState.collect {
                when (it) {
                    is UiStateList.SUCCESS -> {
                        showProgressDialog(false)
                        setData(it.data)
                    }
                    is UiStateList.ERROR -> {
                        showToastMessage(it.message)
                        showProgressDialog(false)

                    }
                    is UiStateList.LOADING -> {

                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }


    }

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }
}