package com.example.elva.ui.health

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.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.example.elva.R
import com.example.elva.databinding.FragmentHealthDashboardBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HealthDashboardFragment : Fragment() {

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

    private val viewModel: HealthDashboardViewModel by viewModels()

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

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

        setupListeners()
        observeState()
    }

    private fun setupListeners() {
        binding.apply {
            // Навигация к календарю
            calendarIcon.setOnClickListener {
                findNavController().navigate(R.id.action_healthDashboard_to_periodCalendar)
            }

            // Клики на карточки для редактирования
            cardCalories.setOnClickListener {
                showCaloriesDialog()
            }

            cardWater.setOnClickListener {
                showWaterDialog()
            }

            cardWeight.setOnClickListener {
                showWeightDialog()
            }

            cardSleep.setOnClickListener {
                showSleepDialog()
            }

            // Журнал
            btnJournal.setOnClickListener {
                findNavController().navigate(R.id.action_healthDashboard_to_healthJournal)
            }
        }
    }

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

    private fun updateUI(state: HealthDashboardState) {
        binding.apply {
            // Калории
            valueCalories.text = state.caloriesConsumed.toString()
            goalCalories.text = getString(R.string.calorie_goal_format, state.caloriesGoal)
            progressCalories.progress = state.caloriesPercent

            // Вода
            valueWater.text = state.waterConsumed.toString()
            goalWater.text = getString(R.string.water_goal_format, state.waterGoal)
            progressWater.progress = state.waterPercent

            // Вес
            if (state.currentWeight != null) {
                valueWeight.text = String.format("%.1f", state.currentWeight)

                if (state.weightChange != 0f) {
                    val sign = if (state.weightChange > 0) "+" else ""
                    changeWeight.text = getString(
                        R.string.weight_change_format,
                        sign,
                        String.format("%.1f", state.weightChange)
                    )
                    changeWeight.visibility = View.VISIBLE
                } else {
                    changeWeight.visibility = View.GONE
                }
            } else {
                valueWeight.text = "—"
                changeWeight.visibility = View.GONE
            }

            // Сон
            valueSleep.text = String.format("%.1f", state.sleepHours)
            goalSleep.text = getString(R.string.sleep_goal_format, state.sleepGoal)
            progressSleep.progress = state.sleepPercent
        }
    }

    private fun showCaloriesDialog() {
        // Показываем диалог для ввода калорий
        CaloriesInputDialog(
            currentValue = viewModel.state.value.caloriesConsumed,
            goal = viewModel.state.value.caloriesGoal,
            onSave = { consumed, goal ->
                viewModel.updateCalories(consumed)
                if (goal != viewModel.state.value.caloriesGoal) {
                    viewModel.setCalorieGoal(goal)
                }
            }
        ).show(childFragmentManager, "calories_dialog")
    }

    private fun showWaterDialog() {
        WaterInputDialog(
            currentValue = viewModel.state.value.waterConsumed,
            goal = viewModel.state.value.waterGoal,
            onSave = { consumed, goal ->
                viewModel.updateWater(consumed)
                if (goal != viewModel.state.value.waterGoal) {
                    viewModel.setWaterGoal(goal)
                }
            }
        ).show(childFragmentManager, "water_dialog")
    }

    private fun showWeightDialog() {
        WeightInputDialog(
            currentValue = viewModel.state.value.currentWeight,
            goal = viewModel.state.value.weightGoal,
            onSave = { weight, goal ->
                viewModel.updateWeight(weight)
                if (goal != null && goal != viewModel.state.value.weightGoal) {
                    viewModel.setWeightGoal(goal)
                }
            }
        ).show(childFragmentManager, "weight_dialog")
    }

    private fun showSleepDialog() {
        SleepInputDialog(
            currentValue = viewModel.state.value.sleepHours,
            goal = viewModel.state.value.sleepGoal,
            quality = viewModel.state.value.sleepQuality,
            onSave = { hours, goal, quality ->
                viewModel.updateSleep(hours, quality)
                if (goal != viewModel.state.value.sleepGoal) {
                    viewModel.setSleepGoal(goal)
                }
            }
        ).show(childFragmentManager, "sleep_dialog")
    }

    override fun onResume() {
        super.onResume()
        viewModel.loadHealthData()
    }

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

