package pl.firmatpp.kierowca.ui

import java.time.LocalDate
import pl.firmatpp.kierowca.data.model.DriverLeaveCalendarEntryDto

data class LeaveRequestsConfig(
    val enabled: Boolean = false,
    val types: List<String> = listOf("URLOP"),
)

object DriverLeaveRequestUiRules {
    fun isFeatureVisible(config: LeaveRequestsConfig?): Boolean =
        config?.enabled == true && config.types.isNotEmpty()

    fun statusLabel(status: String): String =
        when (status) {
            "pending" -> "Oczekuje"
            "approved" -> "Zatwierdzony"
            "rejected" -> "Odrzucony"
            "cancel_requested" -> "Anulowanie do decyzji"
            "cancelled" -> "Anulowany"
            "revoked" -> "Cofnięto decyzję"
            else -> "Nieznany status"
        }

    fun eventActionLabel(action: String): String =
        when (action) {
            "submitted" -> "Wniosek złożony"
            "approved" -> "Wniosek zatwierdzony"
            "rejected" -> "Wniosek odrzucony"
            "revoked" -> "Decyzja cofnięta"
            "cancelled_by_driver" -> "Wniosek anulowany przez kierowcę"
            "cancellation_requested" -> "Kierowca poprosił o anulowanie"
            "cancellation_approved" -> "Anulowanie zatwierdzone"
            "cancellation_rejected" -> "Anulowanie odrzucone"
            else -> "Aktualizacja wniosku"
        }

    fun typeLabel(type: String): String =
        when (type) {
            "URLOP" -> "Urlop"
            "CHOROBOWE" -> "Chorobowe"
            "SZKOLENIE" -> "Szkolenie"
            "WOLNE" -> "Dzień wolny"
            "INNE" -> "Inne"
            else -> type
        }

    fun canCancel(status: String, dateFrom: String, today: LocalDate = LocalDate.now()): Boolean {
        if (status == "pending") return true
        if (status != "approved") return false

        val start = runCatching { LocalDate.parse(dateFrom) }.getOrNull() ?: return false
        return start.isAfter(today)
    }

    fun calendarEntriesForDate(entries: List<DriverLeaveCalendarEntryDto>, date: LocalDate): List<DriverLeaveCalendarEntryDto> =
        entries.filter { entry ->
            val from = entry.dateFrom?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
            val to = entry.dateTo?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
            from != null && to != null && !date.isBefore(from) && !date.isAfter(to)
        }

    fun phoneDialUri(phoneNumber: String?): String? {
        val raw = phoneNumber?.trim().orEmpty()
        if (raw.isBlank()) return null

        val digits = raw.filter { it.isDigit() }
        if (digits.isBlank()) return null

        val normalized = when {
            digits.startsWith("00") -> "+${digits.drop(2)}"
            raw.startsWith("+") -> "+$digits"
            digits.length == 9 -> "+48$digits"
            else -> "+$digits"
        }

        return "tel:$normalized"
    }
}
