package com.example.elva.ui.cycle

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.elva.R
import com.example.elva.databinding.FragmentCycleBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

@AndroidEntryPoint
class CycleFragment : Fragment() {

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

    private val viewModel: CycleViewModel by viewModels()

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

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

        setupUI()
        setupWeekDays()
        observeData()
    }

    private fun setupUI() {
        // Установка текущей даты
        val dateFormat = SimpleDateFormat("MMMM d", Locale.getDefault())
        binding.dateText.text = dateFormat.format(Date())

        // Клики
        binding.editPeriodButton.setOnClickListener {
            // TODO: Открыть диалог редактирования периода
        }

        binding.addButton.setOnClickListener {
            // TODO: Добавить предсказание
        }

        binding.viewAllButton.setOnClickListener {
            // TODO: Показать все циклы
        }
    }

    private fun setupWeekDays() {
        // Создаем кружки для дней недели
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)

        for (i in 1..7) {
            val dayView = createDayView(i, i == 5) // 5 - TODAY
            binding.weekNumbersLayout.addView(dayView)
        }
    }

    private fun createDayView(day: Int, isToday: Boolean): View {
        val context = requireContext()
        val size = (40 * resources.displayMetrics.density).toInt()
        val margin = (8 * resources.displayMetrics.density).toInt()

        val textView = TextView(context).apply {
            text = day.toString()
            textSize = 14f
            gravity = android.view.Gravity.CENTER

            layoutParams = ViewGroup.MarginLayoutParams(size, size).apply {
                setMargins(margin / 2, 0, margin / 2, 0)
            }

            if (isToday) {
                // Сегодня - заполненный круг
                setBackgroundResource(R.drawable.day_circle_today)
                setTextColor(resources.getColor(R.color.white, null))
            } else {
                // Обычный день - пунктирный круг
                setBackgroundResource(R.drawable.day_circle_default)
                setTextColor(resources.getColor(R.color.text_secondary, null))
            }
        }

        return textView
    }

    private fun observeData() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.cycleData.collect { data ->
                    updateUI(data)
                }
            }
        }
    }

    private fun updateUI(data: CycleData) {
        binding.apply {
            // Обновление данных о периоде
            periodDay.text = getString(R.string.period_day, data.periodDay)

            // Предсказания
            ovulationText.text = getString(R.string.ovulation_in_days, data.ovulationInDays)
            nextPeriodText.text = getString(R.string.next_period_in_days, data.nextPeriodInDays)

            // Информация о цикле
            currentCycleText.text = getString(R.string.current_cycle_days, data.cycleDays)

            val dateFormat = SimpleDateFormat("MMM d", Locale.getDefault())
            startedOnText.text = getString(R.string.started_on, dateFormat.format(data.startDate))
        }
    }

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

