package de.tsschulz.tt_tagebuch.app.ui

import android.app.DatePickerDialog
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.Locale

private val UiIsoDateFormatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE
private val UiGermanDateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY)

internal fun parseIsoDateForUi(value: String?): LocalDate? {
    val raw = value?.trim()?.take(10)?.takeIf { it.isNotBlank() } ?: return null
    return try {
        LocalDate.parse(raw, UiIsoDateFormatter)
    } catch (_: DateTimeParseException) {
        null
    }
}

internal fun formatIsoDateForDisplay(value: String?, fallback: String = "-"): String {
    if (value.isNullOrBlank()) return fallback
    return parseIsoDateForUi(value)?.format(UiGermanDateFormatter) ?: value.trim().takeIf { it.isNotBlank() } ?: fallback
}

internal fun todayIsoDate(): String = LocalDate.now().format(UiIsoDateFormatter)

@Composable
internal fun LocalizedDatePickerField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    placeholder: String = "Datum wählen",
) {
    val context = LocalContext.current
    val selected = remember(value) { parseIsoDateForUi(value) }
    val initial = selected ?: LocalDate.now()
    OutlinedButton(
        onClick = {
            DatePickerDialog(
                context,
                { _, year, month, dayOfMonth ->
                    onValueChange(LocalDate.of(year, month + 1, dayOfMonth).format(UiIsoDateFormatter))
                },
                initial.year,
                initial.monthValue - 1,
                initial.dayOfMonth,
            ).show()
        },
        enabled = enabled,
        modifier = modifier.fillMaxWidth().heightIn(min = 48.dp),
    ) {
        val display = selected?.format(UiGermanDateFormatter) ?: value.ifBlank { placeholder }
        Text("$label: $display", maxLines = 2)
    }
}
