package ru.myitschool.work.ui.login

import android.os.Bundle
import android.text.Editable
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.FragmentLoginBinding
import ru.myitschool.work.ui.profile.ProfileDestination
import ru.myitschool.work.utils.TextChangedListener
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.visibleOrGone

@AndroidEntryPoint
class LoginFragment : Fragment(R.layout.fragment_login) {
    private var _binding: FragmentLoginBinding? = null
    private val binding: FragmentLoginBinding get() = _binding!!

    private val viewModel: LoginViewModel by viewModels()

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

    private fun subscribe() {
        viewModel.state.collectWhenStarted(this) { state ->
            binding.error.visibleOrGone(state is LoginViewModel.State.Error)
            binding.loading.visibleOrGone(state is LoginViewModel.State.Loading)
            binding.login.visibleOrGone(state !is LoginViewModel.State.Loading)
            binding.username.isEnabled = state !is LoginViewModel.State.Loading
            when (state) {
                is LoginViewModel.State.Loading -> Unit
                is LoginViewModel.State.Error -> {
                    binding.error.text = state.errorText
                }

                is LoginViewModel.State.Show -> {
                    binding.login.isEnabled = state.isLoginButtonEnabled
                }
            }
        }

        viewModel.action.collectWhenStarted(this) { action ->
            when (action) {
                is LoginViewModel.Action.OpenProfile -> {
                    findNavController().navigate(ProfileDestination) {
                        popUpTo<LoginDestination> { inclusive = true }
                    }
                }
            }
        }
    }

    private fun initCallback() {
        binding.login.setOnClickListener { viewModel.clickLogin() }
        binding.username.addTextChangedListener(object : TextChangedListener() {
            override fun afterTextChanged(s: Editable?) {
                viewModel.inputLogin(s.toString())
            }
        })
    }

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