package pl.firmatpp.kierowca.ui

import java.io.File
import java.time.LocalDate
import java.time.OffsetDateTime
import pl.firmatpp.kierowca.data.model.DriverRouteDto
import pl.firmatpp.kierowca.data.model.RoutePhotoDto
import pl.firmatpp.kierowca.data.upload.PhotoUploadEntity

fun canManageRoutePhotos(selectedDate: String, today: LocalDate = LocalDate.now()): Boolean =
    runCatching { LocalDate.parse(selectedDate).isEqual(today) }.getOrDefault(false)

fun canCompleteRouteFromDriverApp(
    route: DriverRouteDto,
    selectedDate: String,
    today: LocalDate = LocalDate.now(),
): Boolean =
    canManageRoutePhotos(selectedDate, today)
        && route.status in setOf("ZAPLANOWANA", "W TRAKCIE")

fun inlinePhotoGridRows(photoCount: Int): Int =
    if (photoCount <= 0) 0 else (photoCount + 1) / 2

fun visiblePhotoAttachmentCount(serverPhotoCount: Int, localUploadCount: Int): Int =
    serverPhotoCount.coerceAtLeast(0) + localUploadCount.coerceAtLeast(0)

fun queuedPhotoUploadCount(statuses: List<String>): Int =
    statuses.count { status -> status != "CONFIRMED" && status != "CANCELLED" }

fun routePhotoSortEpochMillis(createdAt: String?, takenAt: String?, fallback: Long): Long =
    parseIsoOffsetEpochMillis(createdAt)
        ?: parseIsoOffsetEpochMillis(takenAt)
        ?: fallback

fun confirmedUploadServerPhotoId(status: String, serverPhotoId: String?): String? =
    serverPhotoId?.takeIf { status == "CONFIRMED" && it.isNotBlank() }

fun canRetryPhotoUpload(status: String): Boolean =
    status == "FAILED_RETRYABLE"

fun canShowPhotoUploadFailureDetails(status: String, lastError: String?): Boolean =
    status in setOf("FAILED_RETRYABLE", "FAILED_PERMANENT") && !lastError.isNullOrBlank()

fun localUploadPreviewPhoto(upload: PhotoUploadEntity): RoutePhotoDto? {
    if (upload.localPath.isBlank()) return null

    return RoutePhotoDto(
        id = upload.clientRequestId,
        routeId = upload.routeId,
        clientRequestId = upload.clientRequestId,
        contentSha256 = upload.contentSha256,
        source = upload.source,
        mimeType = upload.mimeType,
        size = upload.size,
        url = File(upload.localPath).toURI().toString(),
        takenAt = upload.takenAt,
        latitude = upload.latitude,
        longitude = upload.longitude,
        locationAccuracyMeters = upload.locationAccuracyMeters,
        createdAt = null,
        canDelete = confirmedUploadServerPhotoId(upload.status, upload.serverPhotoId) != null,
        deleteUntil = null,
    )
}

fun canLaunchCameraWithLocationPolicy(requirePreciseLocation: Boolean, hasFineLocation: Boolean): Boolean =
    !requirePreciseLocation || hasFineLocation

private fun parseIsoOffsetEpochMillis(value: String?): Long? =
    value?.takeIf { it.isNotBlank() }?.let {
        runCatching { OffsetDateTime.parse(it).toInstant().toEpochMilli() }.getOrNull()
    }
