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.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.elva.R
import com.example.elva.databinding.FragmentHealthBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale

@AndroidEntryPoint
class HealthFragment : Fragment() {

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

    private val viewModel: HealthViewModel by viewModels()

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

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

        setupClickListeners()
        observeUiState()
    }

    private fun setupClickListeners() {
        binding.cardCalendar.setOnClickListener {
            // Navigate to calendar fragment
            findNavController().navigate(R.id.action_health_to_calendar)
        }

        binding.cardWater.setOnClickListener {
            showAddWaterDialog()
        }

        binding.cardCalories.setOnClickListener {
            showAddCaloriesDialog()
        }

        binding.cardWeight.setOnClickListener {
            showAddWeightDialog()
        }

        binding.cardSleep.setOnClickListener {
            showAddSleepDialog()
        }
    }

    private fun observeUiState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                when (state) {
                    is HealthUiState.Loading -> {
                        // Show loading
                    }
                    is HealthUiState.Success -> {
                        updateUI(state)
                    }
                    is HealthUiState.Error -> {
                        // Show error
                    }
                }
            }
        }
    }

    private fun updateUI(state: HealthUiState.Success) {
        // Update cycle info
        val dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
            .withLocale(Locale("ru"))

        binding.tvNextPeriod.text = state.cycleStats.nextPeriodStart?.format(dateFormatter) ?: "-"
        binding.tvCycleLength.text = "${state.cycleStats.averageCycleLength} дней"

        // Update water
        val waterPercent = if (state.waterGoal > 0) {
            (state.waterIntake * 100 / state.waterGoal).coerceIn(0, 100)
        } else 0
        binding.progressWater.progress = waterPercent
        binding.tvWaterProgress.text = "${state.waterIntake}/${state.waterGoal} мл"

        // Update calories
        val caloriesPercent = if (state.calorieGoal > 0) {
            (state.caloriesConsumed * 100 / state.calorieGoal).coerceIn(0, 100)
        } else 0
        binding.progressCalories.progress = caloriesPercent
        binding.tvCaloriesProgress.text = "${state.caloriesConsumed}/${state.calorieGoal} ккал"

        // Update weight
        binding.tvWeight.text = if (state.currentWeight != null) {
            "%.1f кг".format(state.currentWeight)
        } else {
            "Нет данных"
        }

        // Update sleep
        val sleepPercent = if (state.sleepGoal > 0 && state.todaySleep != null) {
            ((state.todaySleep / state.sleepGoal) * 100).toInt().coerceIn(0, 100)
        } else 0
        binding.progressSleep.progress = sleepPercent
        binding.tvSleep.text = if (state.todaySleep != null) {
            "%.1f ч".format(state.todaySleep)
        } else {
            "Нет данных"
        }
    }

    private fun showAddWaterDialog() {
        // TODO: Implement water dialog
    }

    private fun showAddCaloriesDialog() {
        // TODO: Implement calories dialog
    }

    private fun showAddWeightDialog() {
        // TODO: Implement weight dialog
    }

    private fun showAddSleepDialog() {
        // TODO: Implement sleep dialog
    }

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

