package com.atridad.ascently.utils

import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter

object DateFormatUtils {

    // ISO 8601 formatter matching iOS date format exactly
    private val ISO_FORMATTER =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX").withZone(ZoneOffset.UTC)

    /** Get current timestamp in iOS-compatible ISO 8601 format */
    fun nowISO8601(): String {
        return ISO_FORMATTER.format(Instant.now())
    }

    /** Parse an iOS-compatible ISO 8601 date string back to Instant */
    fun parseISO8601(dateString: String): Instant? {
        return try {
            Instant.from(ISO_FORMATTER.parse(dateString))
        } catch (_: Exception) {
            try {
                Instant.parse(dateString)
            } catch (_: Exception) {
                null
            }
        }
    }

    /**
     * Format a UTC ISO 8601 date string for display in local timezone This fixes the timezone
     * display issue where UTC dates were shown as local dates
     */
    fun formatDateForDisplay(dateString: String): String {
        val pattern = "MMM dd, yyyy"
        return try {
            val instant = parseISO8601(dateString)
            if (instant != null) {
                val localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                localDateTime.format(DateTimeFormatter.ofPattern(pattern))
            } else {
                // Fallback for malformed dates
                dateString.take(10)
            }
        } catch (_: Exception) {
            dateString.take(10)
        }
    }

    /** Parse a UTC ISO 8601 date string to LocalDateTime in system timezone */
    fun parseToLocalDateTime(dateString: String): LocalDateTime? {
        return try {
            val instant = parseISO8601(dateString)
            instant?.let { LocalDateTime.ofInstant(it, ZoneId.systemDefault()) }
        } catch (_: Exception) {
            null
        }
    }
}
