package com.example.elva.ui.dashboard

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.elva.R
import com.example.elva.databinding.FragmentDashboardBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*

@AndroidEntryPoint
class DashboardFragment : Fragment() {

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

    private val viewModel: HealthViewModel by viewModels()

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

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

        setupDate()
        setupListeners()
        observeState()
    }

    private fun setupDate() {
        val formatter = DateTimeFormatter.ofPattern("d MMMM", Locale("ru"))
        val today = LocalDate.now()
        binding.tvDate.text = "Сегодня, ${today.format(formatter)}"
    }


    private fun setupListeners() {
        binding.apply {
            // Переход к календарю цикла
            cardCycle.setOnClickListener {
                findNavController().navigate(R.id.action_dashboard_to_periodCalendar)
            }

            // Добавление воды
            cardWater.setOnClickListener {
                showWaterDialog()
            }

            // Добавление калорий
            cardCalories.setOnClickListener {
                showCaloriesDialog()
            }

            // Добавление веса
            cardWeight.setOnClickListener {
                showWeightDialog()
            }

            // Добавление сна
            cardSleep.setOnClickListener {
                showSleepDialog()
            }
        }
    }

    private fun observeState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.state.collect { state ->
                updateUI(state)
            }
        }
    }

    private fun updateUI(state: HealthState) {
        binding.apply {
            // Информация о цикле
            val daysUntil = viewModel.getDaysUntilNextPeriod()
            tvCycleInfo.text = if (daysUntil != null) {
                "До менструации: $daysUntil ${getDaysWord(daysUntil)}"
            } else {
                "Нет данных о цикле"
            }

            // Вода
            tvWaterAmount.text = state.waterIntake.amount.toString()
            tvWaterGoal.text = "из ${state.waterIntake.goal} мл"

            // Калории
            tvCaloriesAmount.text = state.calorieIntake.calories.toString()
            tvCaloriesGoal.text = "из ${state.calorieIntake.goal} ккал"

            // Вес
            tvWeightAmount.text = state.latestWeight?.toString() ?: "--"

            // Сон
            tvSleepAmount.text = state.sleepEntry?.hours?.toString() ?: "--"
        }
    }

    private fun getDaysWord(days: Int): String {
        return when {
            days % 10 == 1 && days % 100 != 11 -> "день"
            days % 10 in 2..4 && (days % 100 < 10 || days % 100 >= 20) -> "дня"
            else -> "дней"
        }
    }

    private fun showWaterDialog() {
        val amounts = arrayOf("250 мл", "500 мл", "750 мл", "1000 мл")
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("Добавить воду")
            .setItems(amounts) { _, which ->
                val amount = when (which) {
                    0 -> 250
                    1 -> 500
                    2 -> 750
                    else -> 1000
                }
                viewModel.addWater(amount)
            }
            .setNegativeButton("Отмена", null)
            .show()
    }

    private fun showCaloriesDialog() {
        val view = layoutInflater.inflate(R.layout.dialog_input, null)
        val input = view.findViewById<TextInputEditText>(R.id.editInput)
        input.hint = "Калории"

        MaterialAlertDialogBuilder(requireContext())
            .setTitle("Добавить калории")
            .setView(view)
            .setPositiveButton("Добавить") { _, _ ->
                val calories = input.text.toString().toIntOrNull()
                if (calories != null && calories > 0) {
                    viewModel.addCalories(calories)
                }
            }
            .setNegativeButton("Отмена", null)
            .show()
    }

    private fun showWeightDialog() {
        val view = layoutInflater.inflate(R.layout.dialog_input, null)
        val input = view.findViewById<TextInputEditText>(R.id.editInput)
        input.hint = "Вес (кг)"

        MaterialAlertDialogBuilder(requireContext())
            .setTitle("Записать вес")
            .setView(view)
            .setPositiveButton("Сохранить") { _, _ ->
                val weight = input.text.toString().toFloatOrNull()
                if (weight != null && weight > 0) {
                    viewModel.saveWeight(weight)
                }
            }
            .setNegativeButton("Отмена", null)
            .show()
    }

    private fun showSleepDialog() {
        val view = layoutInflater.inflate(R.layout.dialog_input, null)
        val input = view.findViewById<TextInputEditText>(R.id.editInput)
        input.hint = "Часов сна"

        MaterialAlertDialogBuilder(requireContext())
            .setTitle("Записать сон")
            .setView(view)
            .setPositiveButton("Сохранить") { _, _ ->
                val hours = input.text.toString().toFloatOrNull()
                if (hours != null && hours > 0) {
                    viewModel.saveSleep(hours, com.example.elva.data.models.health.SleepQuality.NORMAL)
                }
            }
            .setNegativeButton("Отмена", null)
            .show()
    }

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


