package ru.myitschool.work.ui.admin

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
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.FragmentAdminBinding
import ru.myitschool.work.ui.main.MainDestination
import ru.myitschool.work.utils.AuthPreferences
import ru.myitschool.work.utils.QrPreferences
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.visibleOrGone

@AndroidEntryPoint
class AdminFragment : Fragment(R.layout.fragment_admin) {
    private var _binding: FragmentAdminBinding? = null
    private val binding: FragmentAdminBinding get() = _binding!!
    private val viewModel: AdminViewModel by viewModels()

    private lateinit var authPreferences: AuthPreferences
    private lateinit var qrPreferences: QrPreferences

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

        authPreferences = AuthPreferences(requireContext())
        qrPreferences = QrPreferences(requireContext())

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentAdminBinding.bind(view)

        setupOpenComponents()
        observeOpenState()
    }

    private fun setupOpenComponents() {
        binding.apply {
            block.setOnClickListener {
                authPreferences.getLogin().toString().let {
                    viewModel.block(
                        it,
                        true
                    )
                }
            }
        }
    }

    private fun observeOpenState() {
        viewModel.state.collectWhenStarted(this) { state ->
            when (state) {
                is AdminViewModel.ResultState.Loading -> {

                }
                is AdminViewModel.ResultState.Success -> {


                }
                is AdminViewModel.ResultState.InvalidCredentials -> {

                }
                is AdminViewModel.ResultState.Error -> {

                }
                AdminViewModel.ResultState.Initial -> {

                }
            }
        }
    }

    private fun visibleAll(isVisible: Boolean) {
        binding.apply {
        }
    }

    private fun navigateToMainScreen() {
        try {
            findNavController().apply {
                popBackStack(MainDestination, false)
                navigate(MainDestination)
            }
        } catch (e: Exception) {
            Log.e("ResultFragment", "Navigation error", e)
            Toast.makeText(context, getText(R.string.errorGoText).toString(), Toast.LENGTH_SHORT).show()
        }
    }

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