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

@AndroidEntryPoint
class DashboardFragmentNew : Fragment() {

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

    private val viewModel: DashboardViewModel by viewModels()

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

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

        setupGreeting()
        setupListeners()
        observeState()

        // Загружаем данные
        viewModel.loadDashboardData()
    }

    private fun setupGreeting() {
        val hour = LocalTime.now().hour
        val greeting = when {
            hour < 12 -> getString(R.string.good_morning)
            hour < 18 -> getString(R.string.good_afternoon)
            else -> getString(R.string.good_evening)
        }
        binding.tvGreeting.text = greeting
    }

    private fun setupListeners() {
        binding.apply {
            // Карточка цикла - открыть календарь периодов
            cardCycle.setOnClickListener {
                findNavController().navigate(R.id.action_dashboard_to_periodCalendar)
            }

            // Карточка календаря - открыть календарь периодов
            cardCalendar.setOnClickListener {
                findNavController().navigate(R.id.action_dashboard_to_periodCalendar)
            }

            // Карточка воды - добавить воду
            cardWater.setOnClickListener {
                showAddWaterDialog()
            }

            // Карточка калорий - открыть экран питания
            cardCalories.setOnClickListener {
                findNavController().navigate(R.id.action_dashboardFragment_to_nav_nutrition)
            }
        }
    }

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

    private fun updateUI(summary: DashboardSummary) {
        binding.apply {
            // Обновляем день цикла
            tvCycleDay.text = getString(R.string.cycle_day_number, summary.cycleDay)

            // Обновляем дни до периода
            summary.nextPeriodDays?.let { days ->
                tvNextPeriod.text = days.toString()
                tvNextPeriodLabel.text = when {
                    days == 0 -> getString(R.string.period_today)
                    days == 1 -> getString(R.string.period_tomorrow)
                    days < 0 -> getString(R.string.period_overdue, -days)
                    else -> resources.getQuantityString(R.plurals.days_until_period, days, days)
                }
            } ?: run {
                tvNextPeriod.text = "—"
                tvNextPeriodLabel.text = getString(R.string.no_data)
            }

            // Обновляем воду
            val waterProgress = (summary.waterProgress * 100).toInt()
            progressWater.progress = waterProgress
            tvWaterAmount.text = getString(
                R.string.water_progress,
                summary.waterAmount,
                summary.waterGoal
            )

            // Обновляем калории
            val caloriesProgress = (summary.caloriesProgress * 100).toInt()
            progressCalories.progress = caloriesProgress
            tvCaloriesAmount.text = getString(
                R.string.calories_progress,
                summary.calories,
                summary.caloriesGoal
            )
        }
    }

    private fun showAddWaterDialog() {
        val amounts = arrayOf("100 мл", "200 мл", "250 мл", "500 мл")
        val amountsValues = arrayOf(100, 200, 250, 500)

        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle(R.string.add_water)
            .setItems(amounts) { _, which ->
                viewModel.addWater(amountsValues[which])
            }
            .show()
    }

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

