package ru.myitschool.work.ui.login

import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import ru.myitschool.work.R
import ru.myitschool.work.databinding.FragmentLoginBinding
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.visibleOrGone
import androidx.navigation.fragment.findNavController
import ru.myitschool.work.ui.main.MainDestination
import ru.myitschool.work.utils.AuthPreferences
import java.util.regex.Pattern

@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()
    private lateinit var authPreferences: AuthPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        authPreferences = AuthPreferences(requireContext())

        if (authPreferences.isLoggedIn()) {
            navigateToMainScreen()
        }
    }

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

        setupLoginComponents()
        observeLoginState()
    }

    private fun setupLoginComponents() {
        binding.username.apply {
            addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    val login = s.toString()
                    binding.login.isEnabled = validateLogin(login)
                }
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            })
        }

        binding.login.setOnClickListener {
            val login = binding.username.text.toString()
            val password = binding.password.text.toString()

            authPreferences.saveLogin(login)
            authPreferences.savePassword(password)

            performLogin()
        }

        binding.loading.visibleOrGone(false)
        binding.error.visibleOrGone(false)
    }

    private fun observeLoginState() {
        viewModel.state.collectWhenStarted(this) { state ->
            when (state) {
                is LoginViewModel.LoginState.Loading -> {
                    binding.loading.visibleOrGone(true)
                    binding.error.visibleOrGone(false)
                }
                is LoginViewModel.LoginState.Success -> {
                    binding.loading.visibleOrGone(false)
                    binding.error.visibleOrGone(false)

                    authPreferences.saveLogin(binding.username.text.toString())
                    authPreferences.savePassword(binding.password.text.toString())

                    authPreferences.saveLoginState(true)

                    navigateToMainScreen()
                }
                is LoginViewModel.LoginState.InvalidCredentials -> {
                    binding.loading.visibleOrGone(false)
                    binding.error.apply {
                        visibleOrGone(true)
                        text = "Неверный логин"
                    }
                }
                is LoginViewModel.LoginState.Error -> {
                    binding.loading.visibleOrGone(false)
                    binding.error.apply {
                        visibleOrGone(true)
                        text = "Ошибка авторизации"
                    }

                    authPreferences.clearLoginState()

                    Log.d("Authentication", "Ошибка авторизации")
                }

                LoginViewModel.LoginState.Initial -> binding.loading.visibleOrGone(false)
            }
        }
    }

    private fun performLogin() {
        lifecycleScope.launch {
            viewModel.authenticate()
        }
    }

    private fun navigateToMainScreen() {
        try {
            findNavController().apply {
                popBackStack(MainDestination, false)
                navigate(MainDestination)
            }
        } catch (e: Exception) {
            Log.e("LoginFragment", "Navigation error", e)
            Toast.makeText(context, "Ошибка перехода", Toast.LENGTH_SHORT).show()
        }
    }

    private fun validateLogin(login: String): Boolean {
        return !(login.isEmpty() ||
                login.length < 3 ||
                Pattern.matches("^[0-9].*", login) ||
                !Pattern.matches("^[a-zA-Z0-9]+$", login))
    }

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