package com.example.elva.ui.auth

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.example.elva.R
import com.example.elva.databinding.FragmentLoginBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class LoginFragment : Fragment() {

    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    private val viewModel: LoginViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupCardHeight()
        setupAnimation()
        setupListeners()
        observeUiState()

        android.util.Log.d("LoginFragment", "LoginFragment loaded, showing login screen")
    }

    private fun setupCardHeight() {
        // Устанавливаем высоту карточки в 60% экрана
        view?.post {
            val screenHeight = resources.displayMetrics.heightPixels
            val cardHeight = (screenHeight * 0.6f).toInt()

            val params = binding.loginCard.layoutParams as ViewGroup.MarginLayoutParams
            params.height = cardHeight
            binding.loginCard.layoutParams = params
        }
    }

    private fun setupAnimation() {
        // Анимация появления не нужна, т.к. Navigation Component уже делает это
    }

    private fun setupListeners() {
        binding.apply {
            loginButton.setOnClickListener {
                val emailOrUsername = usernameInput.text.toString().trim()
                val password = passwordInput.text.toString()
                viewModel.login(emailOrUsername, password)
            }

            registerLink.setOnClickListener {
                // Навигация к экрану регистрации
                findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
            }
        }
    }

    private fun observeUiState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiState.collect { state ->
                    android.util.Log.d("LoginFragment", "UI State changed: $state")
                    when (state) {
                        is LoginUiState.Idle -> {
                            binding.progressBar.isVisible = false
                            setInputsEnabled(true)
                        }
                        is LoginUiState.Loading -> {
                            binding.progressBar.isVisible = true
                            setInputsEnabled(false)
                        }
                        is LoginUiState.Success -> {
                            android.util.Log.d("LoginFragment", "=== LOGIN SUCCESS STATE RECEIVED ===")
                            binding.progressBar.isVisible = false
                            setInputsEnabled(false)

                            // Проверяем статус авторизации
                            val isLoggedIn = viewModel.checkIfLoggedIn()
                            android.util.Log.d("LoginFragment", "After login, isLoggedIn = $isLoggedIn")

                            Toast.makeText(
                                requireContext(),
                                "Вход выполнен успешно!",
                                Toast.LENGTH_SHORT
                            ).show()

                            // Навигация с небольшой задержкой для отображения Toast
                            android.util.Log.d("LoginFragment", "Scheduling navigation to dashboard")
                            view?.postDelayed({
                                if (isAdded && view != null) {
                                    android.util.Log.d("LoginFragment", "Executing delayed navigation")
                                    navigateToDashboard()
                                }
                            }, 300)
                        }
                        is LoginUiState.Error -> {
                            android.util.Log.e("LoginFragment", "Login error: ${state.message}")
                            binding.progressBar.isVisible = false
                            setInputsEnabled(true)
                            Toast.makeText(
                                requireContext(),
                                state.message,
                                Toast.LENGTH_LONG
                            ).show()
                            viewModel.resetState()
                        }
                    }
                }
            }
        }
    }

    private fun setInputsEnabled(enabled: Boolean) {
        binding.apply {
            usernameInput.isEnabled = enabled
            passwordInput.isEnabled = enabled
            loginButton.isEnabled = enabled
            registerLink.isEnabled = enabled
        }
    }

    private fun navigateToDashboard() {
        android.util.Log.d("LoginFragment", "=== STARTING NAVIGATION TO DASHBOARD ===")

        try {
            if (!isAdded) {
                android.util.Log.e("LoginFragment", "Fragment not added, cannot navigate")
                return
            }

            // Проверяем что NavController доступен
            val navController = findNavController()
            android.util.Log.d("LoginFragment", "NavController obtained: ${navController.currentDestination?.label}")

            // Выполняем навигацию
            navController.navigate(R.id.action_login_to_dashboard)
            android.util.Log.d("LoginFragment", "=== NAVIGATION TO DASHBOARD COMPLETED ===")

        } catch (e: IllegalStateException) {
            android.util.Log.e("LoginFragment", "Navigation failed: IllegalStateException", e)
            Toast.makeText(requireContext(), "Ошибка перехода на главный экран", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            android.util.Log.e("LoginFragment", "Navigation failed: ${e.javaClass.simpleName}", e)
            Toast.makeText(requireContext(), "Ошибка навигации: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

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

