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.DialogRegisterBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class RegisterDialogFragment : Fragment() {

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

    private val viewModel: RegisterViewModel by viewModels()

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

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

        setupListeners()
        observeUiState()
    }

    private fun setupListeners() {
        binding.apply {
            registerButton.setOnClickListener {
                val username = usernameInput.text.toString().trim()
                val email = emailInput.text.toString().trim()
                val password = passwordInput.text.toString()

                viewModel.register(
                    username = username,
                    email = email,
                    password = password,
                    confirmPassword = password, // Используем тот же пароль, валидацию делаем на клиенте
                    fullName = null,
                    phone = null
                )
            }

            loginLink.setOnClickListener {
                // Вернуться на экран входа
                findNavController().navigateUp()
            }
        }
    }

    private fun observeUiState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiState.collect { state ->
                    when (state) {
                        is RegisterUiState.Idle -> {
                            binding.progressBar.isVisible = false
                            setInputsEnabled(true)
                        }
                        is RegisterUiState.Loading -> {
                            binding.progressBar.isVisible = true
                            setInputsEnabled(false)
                        }
                        is RegisterUiState.Success -> {
                            binding.progressBar.isVisible = false
                            Toast.makeText(
                                requireContext(),
                                "Регистрация успешна!",
                                Toast.LENGTH_SHORT
                            ).show()

                            // Переход на главный экран
                            findNavController().navigate(R.id.action_loginFragment_to_dashboardFragment)
                        }
                        is RegisterUiState.Error -> {
                            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
            emailInput.isEnabled = enabled
            passwordInput.isEnabled = enabled
            registerButton.isEnabled = enabled
        }
    }

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