package ru.myitschool.work.ui.qr.result

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.databinding.FragmentQrResultBinding
import ru.myitschool.work.ui.qr.scan.QrScanDestination
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.visibleOrGone

@AndroidEntryPoint
class QrResultFragment : Fragment(R.layout.fragment_qr_result) {
    private var _binding: FragmentQrResultBinding? = null
    private val binding: FragmentQrResultBinding get() = _binding!!

    private val viewModel: QrResultViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentQrResultBinding.bind(view)
        initCallback()
        subscribe()
    }

    private fun subscribe() {
        viewModel.state.collectWhenStarted(this) { state ->
            binding.loading.visibleOrGone(state is QrResultViewModel.State.Loading)
            binding.status.visibleOrGone(state is QrResultViewModel.State.Show)
            when (state) {
                is QrResultViewModel.State.Loading -> Unit
                is QrResultViewModel.State.Show -> {
                    binding.status.text = state.status
                }
            }
        }

        viewModel.action.collectWhenStarted(this) { action ->
            when (action) {
                is QrResultViewModel.Action.Close -> {
                    findNavController().popBackStack()
                }
            }
        }
    }

    private fun initCallback() {
        binding.close.setOnClickListener { viewModel.clickClose() }
        findNavController().currentBackStackEntry
            ?.savedStateHandle
            ?.getLiveData<Bundle>(QrScanDestination.REQUEST_KEY)
            ?.observe(viewLifecycleOwner) { result ->
                viewModel.setScanResult(QrScanDestination.getDataIfExist(result))
            }
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}