package com.anypreta.bountyboard.ui.util

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

private val isoParsers: List<SimpleDateFormat> by lazy {
    listOf(
        "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
        "yyyy-MM-dd'T'HH:mm:ssXXX",
        "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
        "yyyy-MM-dd'T'HH:mm:ss'Z'",
    ).map { SimpleDateFormat(it, Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") } }
}

fun parseInstant(s: String?): Date? {
    if (s.isNullOrBlank()) return null
    for (p in isoParsers) {
        try {
            return p.parse(s)
        } catch (_: Exception) {
        }
    }
    return null
}

/** "3h ago", "2d ago", "just now". */
fun relativeTime(s: String?): String {
    val date = parseInstant(s) ?: return ""
    val diff = System.currentTimeMillis() - date.time
    if (diff < 0) return "just now"
    val sec = diff / 1000
    val min = sec / 60
    val hr = min / 60
    val day = hr / 24
    return when {
        sec < 45 -> "just now"
        min < 60 -> "${min}m ago"
        hr < 24 -> "${hr}h ago"
        day < 30 -> "${day}d ago"
        day < 365 -> "${day / 30}mo ago"
        else -> "${day / 365}y ago"
    }
}

private val shortDate = SimpleDateFormat("MMM d, yyyy", Locale.US)
private val timeOnly = SimpleDateFormat("h:mm a", Locale.US)
private val dayTime = SimpleDateFormat("MMM d, h:mm a", Locale.US)

fun shortDate(s: String?): String = parseInstant(s)?.let { shortDate.format(it) } ?: ""
fun clockTime(s: String?): String = parseInstant(s)?.let { timeOnly.format(it) } ?: ""
fun dayAndTime(s: String?): String = parseInstant(s)?.let { dayTime.format(it) } ?: ""

/** Bounty values render as plain numbers (no currency) prefixed by ◈ at the UI layer. */
fun formatBounty(value: Double): String =
    if (value == value.toLong().toDouble()) value.toLong().toString()
    else String.format(Locale.US, "%.2f", value)

fun formatMinutes(total: Int): String {
    if (total <= 0) return "0m"
    val h = total / 60
    val m = total % 60
    return when {
        h > 0 && m > 0 -> "${h}h ${m}m"
        h > 0 -> "${h}h"
        else -> "${m}m"
    }
}

fun statusLabel(status: String): String = when (status) {
    "imported" -> "Imported"
    "atomizing" -> "Atomizing"
    "atomized" -> "Atomized"
    "published" -> "Published"
    "claim_requested" -> "Claim requested"
    "assigned" -> "Assigned"
    "in_progress" -> "In progress"
    "in_review" -> "In review"
    "changes_requested" -> "Changes requested"
    "approved" -> "Approved"
    "archived" -> "Archived"
    else -> status.replace('_', ' ').replaceFirstChar { it.uppercase() }
}

/** Strip server-sanitized HTML to plain text for compact previews. */
fun htmlToPlain(html: String): String =
    html.replace(Regex("<br\\s*/?>"), "\n")
        .replace(Regex("</p>|</li>|</blockquote>"), "\n")
        .replace(Regex("<[^>]+>"), "")
        .replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
        .replace("&quot;", "\"").replace("&#39;", "'").replace("&nbsp;", " ")
        .trim()
