package com.example.elva.ui.profile

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.data.models.user.UserProfile
import com.example.elva.databinding.FragmentProfileBinding
import com.example.elva.util.AuthManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class ProfileFragment : Fragment() {

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

    private val viewModel: ProfileViewModel by viewModels()

    @Inject
    lateinit var authManager: AuthManager

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

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

        setupUi()
        observeState()
    }

    private fun setupUi() {
        binding.editProfileBtn.setOnClickListener {
            Toast.makeText(context, "Редактирование профиля будет доступно скоро", Toast.LENGTH_SHORT).show()
        }

        binding.logoutBtn.setOnClickListener {
            logout()
        }
    }

    private fun logout() {
        lifecycleScope.launch {
            authManager.logout()
            findNavController().navigate(R.id.action_profileFragment_to_loginFragment)
        }
    }

    private fun observeState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiState.collect { state ->
                    when (state) {
                        is ProfileUiState.Loading -> {
                            showLoading(true)
                        }
                        is ProfileUiState.Success -> {
                            showLoading(false)
                            displayProfile(state.profile)
                        }
                        is ProfileUiState.Error -> {
                            showLoading(false)
                            Toast.makeText(context, state.message, Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
        }
    }

    private fun showLoading(isLoading: Boolean) {
        binding.progressBar.isVisible = isLoading
        binding.profileContent.isVisible = !isLoading
    }

    private fun displayProfile(profile: UserProfile) {
        with(binding) {
            usernameText.text = profile.username ?: "Не указано"
            emailText.text = profile.email

            val fullName = when {
                !profile.fullName.isNullOrBlank() -> profile.fullName
                !profile.firstName.isNullOrBlank() || !profile.lastName.isNullOrBlank() -> {
                    "${profile.firstName ?: ""} ${profile.lastName ?: ""}".trim()
                }
                else -> "Не указано"
            }
            fullNameText.text = fullName

            phoneText.text = profile.phoneNumber ?: profile.phone ?: "Не указано"

            locationSharingText.text = if (profile.locationSharingEnabled) "✅ Включено" else "❌ Выключено"
            emergencyNotificationsText.text = if (profile.emergencyNotificationsEnabled) "✅ Включено" else "❌ Выключено"
        }
    }

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

