package de.tsschulz.tt_tagebuch.shared.api.models

import kotlinx.serialization.Serializable

@Serializable
data class DiaryDateActivityItem(
    val id: Int,
    val orderId: Int = 0,
    val isTimeblock: Boolean = false,
    val duration: Int? = null,
    val durationText: String? = null,
    /** Trainingsgruppe (Tabellen `Group`) für getrennte Pläne am selben Tag. */
    val groupId: Int? = null,
    val planGroup: DiaryPlanGroupSummary? = null,
    val predefinedActivity: PredefinedActivitySummary? = null,
    @Serializable(with = FlexibleNullableDrawingDataSerializer::class)
    val drawingData: String? = null,
    val groupActivities: List<GroupActivitySummary> = emptyList(),
)

@Serializable
data class DiaryPlanGroupSummary(
    val id: Int? = null,
    val name: String? = null,
)

@Serializable
data class PredefinedActivitySummary(
    val id: Int? = null,
    val name: String? = null,
    val code: String? = null,
    /** Wie Backend: z. B. `/api/predefined-activities/…/image/…` */
    val imageLink: String? = null,
    val imageUrl: String? = null,
    @Serializable(with = FlexibleNullableDrawingDataSerializer::class)
    val drawingData: String? = null,
    val images: List<PredefinedActivityImageSummary> = emptyList(),
)

@Serializable
data class PredefinedActivityImageSummary(
    val id: Int? = null,
    val imagePath: String? = null,
    @Serializable(with = FlexibleNullableDrawingDataSerializer::class)
    val drawingData: String? = null,
)

@Serializable
data class GroupActivitySummary(
    val id: Int? = null,
    val orderId: Int? = null,
    val groupId: Int? = null,
    val duration: Int? = null,
    val durationText: String? = null,
    val groupPredefinedActivity: PredefinedActivitySummary? = null,
    @Serializable(with = FlexibleNullableDrawingDataSerializer::class)
    val drawingData: String? = null,
)

fun PredefinedActivitySummary?.displayLabel(): String {
    if (this == null) return ""
    val n = name?.trim().orEmpty()
    if (n.isNotEmpty()) return n
    val c = code?.trim().orEmpty()
    if (c.isNotEmpty()) return c
    return ""
}

fun DiaryDateActivityItem.displayTitle(fallbackTimeblock: String): String {
    val label = predefinedActivity.displayLabel()
    if (label.isNotEmpty()) return label
    return if (isTimeblock) fallbackTimeblock else ""
}

fun PredefinedActivitySummary?.drawingDataForDisplay(): String? {
    if (this == null) return null
    return drawingData?.takeIf { it.isNotBlank() }
        ?: images.firstNotNullOfOrNull { image -> image.drawingData?.takeIf { it.isNotBlank() } }
}
