package com.example.elva.ui.dashboard

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.elva.R
import com.example.elva.databinding.ItemCalendarDayBinding

data class CalendarDay(
    val day: Int,
    val dayType: DayType,
    val isCurrentDay: Boolean = false
)

enum class DayType {
    NORMAL,
    PERIOD,
    OVULATION,
    FERTILE,
    EMPTY
}

class CalendarAdapter : ListAdapter<CalendarDay, CalendarAdapter.DayViewHolder>(DayDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayViewHolder {
        val binding = ItemCalendarDayBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return DayViewHolder(binding)
    }

    override fun onBindViewHolder(holder: DayViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class DayViewHolder(private val binding: ItemCalendarDayBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(calendarDay: CalendarDay) {
            if (calendarDay.dayType == DayType.EMPTY) {
                binding.dayText.text = ""
                binding.dayContainer.background = null
                return
            }

            binding.dayText.text = calendarDay.day.toString()

            // Устанавливаем фон в зависимости от типа дня
            val backgroundRes = when (calendarDay.dayType) {
                DayType.PERIOD -> R.drawable.day_circle_period
                DayType.OVULATION -> R.drawable.day_circle_ovulation
                DayType.FERTILE -> R.drawable.day_circle_fertile
                else -> if (calendarDay.isCurrentDay) R.drawable.day_circle_current else R.drawable.day_circle_default
            }

            binding.dayContainer.background = ContextCompat.getDrawable(
                binding.root.context,
                backgroundRes
            )

            // Цвет текста для текущего дня
            if (calendarDay.isCurrentDay && calendarDay.dayType == DayType.NORMAL) {
                binding.dayText.setTextColor(
                    ContextCompat.getColor(binding.root.context, R.color.primary)
                )
            } else {
                binding.dayText.setTextColor(
                    ContextCompat.getColor(binding.root.context, R.color.text_primary)
                )
            }
        }
    }

    class DayDiffCallback : DiffUtil.ItemCallback<CalendarDay>() {
        override fun areItemsTheSame(oldItem: CalendarDay, newItem: CalendarDay): Boolean {
            return oldItem.day == newItem.day
        }

        override fun areContentsTheSame(oldItem: CalendarDay, newItem: CalendarDay): Boolean {
            return oldItem == newItem
        }
    }
}

