package ru.forbion.f7cloud.core.designsystem

import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.Locale

fun formatNotificationRelativeTime(isoDatetime: String): String {
    if (isoDatetime.isBlank()) return ""
    val instant = runCatching { Instant.parse(isoDatetime) }.getOrNull() ?: return ""
    val zone = ZoneId.systemDefault()
    val date = instant.atZone(zone).toLocalDate()
    val today = LocalDate.now(zone)
    val days = ChronoUnit.DAYS.between(date, today)
    return when {
        days == 0L -> "сегодня"
        days == 1L -> "вчера"
        days == 2L -> "позавчера"
        days in 3..6 -> "$days ${daysLabel(days)} назад"
        else -> DateTimeFormatter.ofPattern("d MMM", Locale("ru")).format(date)
    }
}

private fun daysLabel(days: Long): String {
    val mod10 = (days % 10).toInt()
    val mod100 = (days % 100).toInt()
    return when {
        mod10 == 1 && mod100 != 11 -> "день"
        mod10 in 2..4 && mod100 !in 12..14 -> "дня"
        else -> "дней"
    }
}
