package pl.firmatpp.kierowca.sync

import java.time.LocalDate
import java.util.Locale
import java.time.DayOfWeek
import java.time.format.DateTimeFormatter
import pl.firmatpp.kierowca.data.model.DriverRouteDto

object NewRouteNotificationFormatter {
    private val polishLocale = Locale("pl", "PL")
    private val monthFormatter = DateTimeFormatter.ofPattern("d MMMM", polishLocale)

    fun title(routeDate: String?, today: LocalDate = LocalDate.now()): String {
        val label = humanDate(routeDate, today) ?: return "Nowy kurs"

        return "Nowy kurs: $label"
    }

    fun collapsedText(route: DriverRouteDto): String =
        listOf(route.originName, route.destinationName)
            .filter(String::isNotBlank)
            .joinToString(" → ")
            .ifBlank { route.relationLabel }
            .let { relation ->
                val contract = route.contractName?.takeIf(String::isNotBlank) ?: route.contractCode
                if (contract.isNullOrBlank()) relation else "$relation · $contract"
            }

    fun expandedText(route: DriverRouteDto): String {
        val contract = route.contractName?.takeIf(String::isNotBlank) ?: route.contractCode ?: "Brak nazwy kontraktu"

        return listOf(
            "Skąd: ${route.originName.ifBlank { "Nie podano" }}",
            "Dokąd: ${route.destinationName.ifBlank { "Nie podano" }}",
            "Kontrakt: $contract",
        ).joinToString("\n")
    }

    private fun humanDate(routeDate: String?, today: LocalDate): String? {
        val date = runCatching { routeDate?.let(LocalDate::parse) }.getOrNull() ?: return null

        return when {
            date == today -> "dzisiaj"
            date == today.plusDays(1) -> "jutro"
            date.isAfter(today.plusDays(1)) && !date.isAfter(today.plusDays(7)) ->
                "w ${weekdayAccusative(date.dayOfWeek)}"
            else -> date.format(monthFormatter).lowercase(polishLocale)
        }
    }

    private fun weekdayAccusative(dayOfWeek: DayOfWeek): String =
        when (dayOfWeek) {
            DayOfWeek.MONDAY -> "poniedziałek"
            DayOfWeek.TUESDAY -> "wtorek"
            DayOfWeek.WEDNESDAY -> "środę"
            DayOfWeek.THURSDAY -> "czwartek"
            DayOfWeek.FRIDAY -> "piątek"
            DayOfWeek.SATURDAY -> "sobotę"
            DayOfWeek.SUNDAY -> "niedzielę"
        }
}
