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.mobiuz.presentation.card.dialog.MessageDialogFragment
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.coreui.extension.formattedCardNumber
import uz.agr.sdk.coreui.extension.visible
import uz.agr.sdk.coreui.ui.decoration.EndOffsetItemDecoration
import uz.agr.sdk.coreui.ui.decoration.StartOffsetItemDecoration
import uz.agr.sdk.pgw_core.mobi.BaseListener
import uz.agr.sdk.pgw_core.mobi.MobiUz
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 {
//                addCard()
                navController.navigate(R.id.addCardFragment)
            }

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

            swipeToRefresh.setColorSchemeResources(
                uz.agr.mobiuz.R.color.agr_black,
                uz.agr.mobiuz.R.color.agr_mobi_uz_colorAccent
            )
            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(uz.agr.mobiuz.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 {
            MobiUz.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 hasCards() {
//        MobiUz.hasCards(object : BaseListener<Boolean> {
//            override fun error(message: String) {
//
//            }
//
//            override fun loading(boolean: Boolean) {
//
//            }
//
//            override fun success(data: Boolean) {
//                getAllCards()
//            }
//        })
//    }
//
//    private fun getAllCards() {
//        MobiUz.getAllCards(object : CardListenerMobi<CardInfo> {
//            override fun error(message: String) {
//
//            }
//
//            override fun loading(boolean: Boolean) {
//
//            }
//
//            override fun local(localData: List<CardInfo>) {
//                setData(localData)
//            }
//
//            override fun server(serverData: List<CardInfo>) {
//                setData(serverData)
//            }
//        })
//    }

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

//    private fun addCard() {
//        MobiUz.registerCard("998990552109", "8600312917291250", "0325", object : BaseListener<CardRegistration> {
//            override fun error(message: String) {
//                Log.e("TTT", "error:$message")
//            }
//
//            override fun loading(boolean: Boolean) {
//                Log.e("TTT", "loading:$boolean")
//            }
//
//            override fun success(data: CardRegistration) {
//                Log.e("TTT", "success:${data.maskedPhoneNumber}")
//            }
//        })
//    }
//
//    private fun cardConfirm(cardId: String, code: String) {
//        MobiUz.cardConfirmSms(cardId, code, object : BaseListener<CardInfo> {
//            override fun error(message: String) {
//
//            }
//
//            override fun loading(boolean: Boolean) {
//
//            }
//
//            override fun success(data: CardInfo) {
//
//            }
//        })
//
//
//    }
//
//    private fun delete(card: CardInfo) {
//        MobiUz.deleteCard(card)
//    }


    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()
    }
}