package de.tsschulz.timeclock.ui

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.tsschulz.timeclock.data.api.WeekDayDto
import de.tsschulz.timeclock.data.api.WeekOverviewDto
import de.tsschulz.timeclock.data.api.WorkBlockDto
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.tsschulz.timeclock.ui.admin.AdminViewModel
import de.tsschulz.timeclock.ui.admin.HolidaysAdminScreen
import de.tsschulz.timeclock.ui.admin.RolesAdminScreen
import de.tsschulz.timeclock.ui.auth.AuthViewModel
import de.tsschulz.timeclock.ui.auth.LoginScreen
import de.tsschulz.timeclock.ui.booking.BookingViewModel
import de.tsschulz.timeclock.ui.booking.CalendarScreen
import de.tsschulz.timeclock.ui.booking.SickScreen
import de.tsschulz.timeclock.ui.booking.TimefixScreen
import de.tsschulz.timeclock.ui.booking.VacationScreen
import de.tsschulz.timeclock.ui.booking.WorkdaysScreen
import de.tsschulz.timeclock.ui.components.TcButton
import de.tsschulz.timeclock.ui.components.TcCard
import de.tsschulz.timeclock.ui.components.TcError
import de.tsschulz.timeclock.ui.components.TcLoading
import de.tsschulz.timeclock.ui.components.TcScaffold
import de.tsschulz.timeclock.ui.components.TcTextField
import de.tsschulz.timeclock.ui.model.AppRoute
import de.tsschulz.timeclock.ui.model.ButtonVariant
import de.tsschulz.timeclock.ui.model.adminSections
import de.tsschulz.timeclock.ui.model.userSections
import de.tsschulz.timeclock.ui.settings.InviteScreen
import de.tsschulz.timeclock.ui.settings.PasswordScreen
import de.tsschulz.timeclock.ui.settings.PermissionsScreen
import de.tsschulz.timeclock.ui.settings.ProfileScreen
import de.tsschulz.timeclock.ui.settings.SettingsViewModel
import de.tsschulz.timeclock.ui.settings.TimewishScreen
import de.tsschulz.timeclock.ui.theme.TcColors
import de.tsschulz.timeclock.ui.theme.TcRadius
import de.tsschulz.timeclock.ui.theme.TcSpacing
import de.tsschulz.timeclock.ui.time.EntriesScreen
import de.tsschulz.timeclock.ui.time.StatsScreen
import de.tsschulz.timeclock.ui.time.TimeViewModel
import java.time.LocalDate
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

@Composable
fun TimeClockApp(
    authViewModel: AuthViewModel,
    timeViewModel: TimeViewModel,
    bookingViewModel: BookingViewModel,
    settingsViewModel: SettingsViewModel,
    adminViewModel: AdminViewModel,
) {
    val authState by authViewModel.uiState.collectAsStateWithLifecycle()
    val timeState by timeViewModel.uiState.collectAsStateWithLifecycle()
    val bookingState by bookingViewModel.uiState.collectAsStateWithLifecycle()
    val settingsState by settingsViewModel.uiState.collectAsStateWithLifecycle()
    val adminState by adminViewModel.uiState.collectAsStateWithLifecycle()
    val context = LocalContext.current
    val openUrl: (String) -> Unit = { url ->
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
    }
    LaunchedEffect(settingsState.googleLinkUrl) {
        settingsState.googleLinkUrl?.let {
            openUrl(it)
            settingsViewModel.consumeGoogleLinkUrl()
        }
    }

    if (!authState.isAuthenticated) {
        LaunchedEffect(Unit) { timeViewModel.stop() }
        LoginScreen(
            state = authState,
            onLogin = { e, p, action -> authViewModel.login(e, p, action) },
            onGoogleLogin = { openUrl(authViewModel.googleLoginUrl()) },
            onLinkExistingGoogleAccount = { e, p -> authViewModel.linkExistingOAuthAccount(e, p) },
            onRetryBootstrap = { authViewModel.retryBootstrap() },
        )
        return
    }

    val user = authState.user
    if (user == null) {
        LoginScreen(
            state = authState,
            onLogin = { e, p, action -> authViewModel.login(e, p, action) },
            onGoogleLogin = { openUrl(authViewModel.googleLoginUrl()) },
            onLinkExistingGoogleAccount = { e, p -> authViewModel.linkExistingOAuthAccount(e, p) },
            onRetryBootstrap = { authViewModel.retryBootstrap() },
        )
        return
    }

    val sections = if (user.isAdmin) adminSections else userSections
    LaunchedEffect(user.id) { timeViewModel.start() }
    LaunchedEffect(user.id) { settingsViewModel.loadPhase5() }
    LaunchedEffect(user.id, user.isAdmin) { adminViewModel.loadPhase6(user.isAdmin) }

    var selectedRoute by remember { mutableStateOf(AppRoute.Week) }

    BoxWithConstraints(modifier = Modifier.background(TcColors.Background)) {
        val isTablet = maxWidth >= 840.dp
        TcScaffold(
            title = selectedRoute.title,
            userName = user.fullName,
            sections = sections,
            selectedRoute = selectedRoute,
            isTablet = isTablet,
            statusRows = timeState.statusRows,
            primaryStatusAction = timeState.primaryAction,
            secondaryStatusAction = timeState.secondaryAction,
            onRouteSelected = { selectedRoute = it },
            onLogout = {
                timeViewModel.stop()
                authViewModel.logout()
            },
            onStatusAction = { action ->
                action.clockAction?.let { timeViewModel.clock(it) }
            },
        ) {
            timeState.error?.let { TcError(it) }
            DemoScreen(
                route = selectedRoute,
                isTablet = isTablet,
                week = timeState.week,
                weekLoading = timeState.weekLoading,
                weekError = timeState.weekError,
                weekOffset = timeState.weekOffset,
                onWeekOffset = { timeViewModel.loadWeek(it) },
                timeState = timeState,
                timeViewModel = timeViewModel,
                bookingState = bookingState,
                bookingViewModel = bookingViewModel,
                settingsState = settingsState,
                settingsViewModel = settingsViewModel,
                adminState = adminState,
                adminViewModel = adminViewModel,
            )
        }
    }
}

@Composable
private fun DemoScreen(
    route: AppRoute,
    isTablet: Boolean,
    week: WeekOverviewDto?,
    weekLoading: Boolean,
    weekError: String?,
    weekOffset: Int,
    onWeekOffset: (Int) -> Unit,
    timeState: de.tsschulz.timeclock.ui.time.TimeUiState,
    timeViewModel: TimeViewModel,
    bookingState: de.tsschulz.timeclock.ui.booking.BookingUiState,
    bookingViewModel: BookingViewModel,
    settingsState: de.tsschulz.timeclock.ui.settings.SettingsUiState,
    settingsViewModel: SettingsViewModel,
    adminState: de.tsschulz.timeclock.ui.admin.AdminUiState,
    adminViewModel: AdminViewModel,
) {
    when (route) {
        AppRoute.Week -> WeekOverviewScreen(
            week = week,
            loading = weekLoading,
            error = weekError,
            weekOffset = weekOffset,
            onWeekOffset = onWeekOffset,
            isTablet = isTablet,
        )
        AppRoute.Timefix -> {
            LaunchedEffect(route) { bookingViewModel.loadTimefix() }
            TimefixScreen(
                state = bookingState,
                isTablet = isTablet,
                onDate = { bookingViewModel.setTimefixDate(it) },
                onCreate = { id, date, time, action -> bookingViewModel.createTimefix(id, date, time, action) },
                onDelete = { bookingViewModel.deleteTimefix(it) },
            )
        }
        AppRoute.Vacation -> {
            LaunchedEffect(route) { bookingViewModel.loadVacations() }
            VacationScreen(
                state = bookingState,
                isTablet = isTablet,
                onCreate = { type, start, end -> bookingViewModel.createVacation(type, start, end) },
                onDelete = { bookingViewModel.deleteVacation(it) },
            )
        }
        AppRoute.Sick -> {
            LaunchedEffect(route) { bookingViewModel.loadSick() }
            SickScreen(
                state = bookingState,
                isTablet = isTablet,
                onCreate = { type, start, end -> bookingViewModel.createSick(type, start, end) },
                onDelete = { bookingViewModel.deleteSick(it) },
            )
        }
        AppRoute.Workdays -> {
            LaunchedEffect(route) { bookingViewModel.loadWorkdays(bookingState.workdaysYear) }
            WorkdaysScreen(state = bookingState, onYear = { bookingViewModel.loadWorkdays(it) })
        }
        AppRoute.Calendar -> {
            LaunchedEffect(route) { bookingViewModel.loadCalendar(bookingState.calendarYear, bookingState.calendarMonth) }
            CalendarScreen(state = bookingState, onMonth = { bookingViewModel.changeCalendarMonth(it) })
        }
        AppRoute.Entries -> {
            LaunchedEffect(Unit) { timeViewModel.loadEntries() }
            EntriesScreen(
                entries = timeState.entries,
                loading = timeState.entriesLoading,
                error = timeState.entriesError,
                onRefresh = { timeViewModel.loadEntries() },
                onDelete = { timeViewModel.deleteEntry(it) },
            )
        }
        AppRoute.Stats -> {
            LaunchedEffect(Unit) { timeViewModel.loadStats() }
            StatsScreen(
                stats = timeState.stats,
                loading = timeState.statsLoading,
                error = timeState.statsError,
                onRefresh = { timeViewModel.loadStats() },
            )
        }
        AppRoute.Export -> TcCard { Text("Export ist in der Android-App deaktiviert.", color = TcColors.TextMuted) }
        AppRoute.Profile -> {
            LaunchedEffect(route) { settingsViewModel.loadProfile() }
            ProfileScreen(
                state = settingsState,
                isTablet = isTablet,
                onSave = { name, stateId, weekWorkdays, dailyHours, titleType ->
                    settingsViewModel.updateProfile(name, stateId, weekWorkdays, dailyHours, titleType)
                },
                onLinkGoogle = { settingsViewModel.startGoogleLink() },
            )
        }
        AppRoute.Password -> PasswordScreen(
            state = settingsState,
            onChange = { old, new, confirm -> settingsViewModel.changePassword(old, new, confirm) },
        )
        AppRoute.Timewish -> {
            LaunchedEffect(route) { settingsViewModel.loadTimewishes() }
            TimewishScreen(
                state = settingsState,
                isTablet = isTablet,
                onCreate = { day, type, hours, start, end -> settingsViewModel.createTimewish(day, type, hours, start, end) },
                onDelete = { settingsViewModel.deleteTimewish(it) },
            )
        }
        AppRoute.Permissions -> {
            LaunchedEffect(route) { settingsViewModel.loadWatchers() }
            PermissionsScreen(
                state = settingsState,
                isTablet = isTablet,
                onAdd = { settingsViewModel.addWatcher(it) },
                onDelete = { settingsViewModel.deleteWatcher(it) },
            )
        }
        AppRoute.Invite -> {
            LaunchedEffect(route) { settingsViewModel.loadInvites() }
            InviteScreen(
                state = settingsState,
                isTablet = isTablet,
                onSend = { settingsViewModel.sendInvite(it) },
            )
        }
        AppRoute.Holidays -> HolidaysAdminScreen(
            state = adminState,
            isTablet = isTablet,
            onCreate = { date, hours, description, stateIds -> adminViewModel.createHoliday(date, hours, description, stateIds) },
            onDelete = { adminViewModel.deleteHoliday(it) },
        )
        AppRoute.Roles -> RolesAdminScreen(
            state = adminState,
            onUpdateRole = { id, role -> adminViewModel.updateUserRole(id, role) },
        )
    }
}

@Composable
private fun WeekOverviewScreen(
    week: WeekOverviewDto?,
    loading: Boolean,
    error: String?,
    weekOffset: Int,
    onWeekOffset: (Int) -> Unit,
    isTablet: Boolean,
) {
    TcCard {
        Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
            TcButton("← Vorherige Woche", variant = ButtonVariant.Secondary, onClick = { onWeekOffset(weekOffset - 1) })
            Text(
                text = week?.rangeText() ?: "Wochenübersicht",
                color = TcColors.Text,
                fontSize = 18.sp,
                fontWeight = FontWeight.SemiBold,
            )
            TcButton("Nächste Woche →", variant = ButtonVariant.Secondary, onClick = { onWeekOffset(weekOffset + 1) })
        }
    }

    when {
        loading -> TcLoading("Lade Wochenübersicht...")
        error != null -> TcError(error)
        week == null -> TcCard { Text("Keine Wochenübersicht vorhanden", color = TcColors.TextMuted) }
        isTablet -> WeekTablet(week)
        else -> WeekPhone(week)
    }
}

@Composable
private fun WeekTablet(week: WeekOverviewDto) {
    WeekTable(week, compact = false)
}

@Composable
private fun WeekPhone(week: WeekOverviewDto) {
    WeekTable(week, compact = true)
}

@Composable
private fun WeekTable(week: WeekOverviewDto, compact: Boolean) {
    TcCard {
        if (!compact) {
            WeekHeaderRow()
        }
        Column(verticalArrangement = Arrangement.spacedBy(TcSpacing.Sm)) {
            week.days.forEach { day -> WeekDayRow(day, compact) }
            WeekSummaryRows(week, compact)
        }
    }
}

@Composable
private fun WeekHeaderRow() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(TcColors.Background, RoundedCornerShape(TcRadius.Medium))
            .padding(horizontal = TcSpacing.Md, vertical = TcSpacing.Sm),
        horizontalArrangement = Arrangement.spacedBy(TcSpacing.Md),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        WeekCell("Tag", weight = 1.0f, header = true)
        WeekCell("Datum", weight = 1.0f, header = true)
        WeekCell("Zeiten", weight = 2.4f, header = true)
        WeekCell("Arbeitszeit", weight = 1.4f, header = true)
        WeekCell("Status", weight = 1.2f, header = true)
    }
}

@Composable
private fun WeekDayRow(day: WeekDayDto, compact: Boolean) {
    val bg = if (day.isToday) TcColors.ActiveMenu else TcColors.Background
    if (compact) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(bg, RoundedCornerShape(TcRadius.Medium))
                .border(1.dp, TcColors.Border, RoundedCornerShape(TcRadius.Medium))
                .padding(TcSpacing.Md),
            verticalArrangement = Arrangement.spacedBy(TcSpacing.Sm),
        ) {
            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                Text(day.name ?: "Tag", color = TcColors.Text, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
                Text(day.date.toDisplayDate(), color = TcColors.TextMuted, fontSize = 14.sp)
            }
            WeekDetailBlock("Zeiten", day.timeLines())
            WeekDetailBlock("Arbeitszeit", day.workTotalLines())
            day.statusText?.let { WeekStatusBadge(it) }
        }
    } else {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(bg, RoundedCornerShape(TcRadius.Medium))
                .border(1.dp, TcColors.Border, RoundedCornerShape(TcRadius.Medium))
                .padding(TcSpacing.Md),
            horizontalArrangement = Arrangement.spacedBy(TcSpacing.Md),
            verticalAlignment = Alignment.Top,
        ) {
            WeekCell(day.name ?: "Tag", weight = 1.0f, strong = true)
            WeekCell(day.date.toDisplayDate(), weight = 1.0f)
            WeekMultilineCell(day.timeLines(), weight = 2.4f)
            WeekMultilineCell(day.workTotalLines(), weight = 1.4f)
            WeekCell(day.statusText ?: "—", weight = 1.2f)
        }
    }
}

@Composable
private fun WeekSummaryRows(week: WeekOverviewDto, compact: Boolean) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(TcColors.Card, RoundedCornerShape(TcRadius.Medium))
            .border(1.dp, TcColors.Border, RoundedCornerShape(TcRadius.Medium))
            .padding(TcSpacing.Md),
        verticalArrangement = Arrangement.spacedBy(TcSpacing.Sm),
    ) {
        WeekSummaryLine("Wochensumme", week.weekTotal ?: "0:00", compact)
        if (week.nonWorkingDays > 0) {
            WeekSummaryLine(
                "Arbeitsfreie Tage (${week.nonWorkingDays})",
                week.nonWorkingTotal ?: "0:00",
                compact,
                week.nonWorkingDetails.joinToString { "${it.date.toDisplayDate()}: ${it.type ?: "frei"} (${it.hours.toHourLabel()}h)" },
            )
        }
        WeekSummaryLine("Gesamtsumme", week.totalAll ?: week.weekTotal ?: "0:00", compact)
    }
}

@Composable
private fun WeekSummaryLine(label: String, value: String, compact: Boolean, detail: String? = null) {
    if (compact) {
        Column {
            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                Text(label, color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
                Text(value, color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
            }
            detail?.let { Text(it, color = TcColors.TextMuted, fontSize = 12.sp) }
        }
    } else {
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(TcSpacing.Md)) {
            Text(label, color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(5.4f))
            Text(value, color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1.4f))
            Text(detail.orEmpty(), color = TcColors.TextMuted, fontSize = 12.sp, modifier = Modifier.weight(1.2f))
        }
    }
}

@Composable
private fun WeekDetailBlock(label: String, lines: List<String>) {
    Text(label, color = TcColors.TextMuted, fontSize = 13.sp, fontWeight = FontWeight.Medium)
    lines.ifEmpty { listOf("—") }.forEach { line ->
        Text(line, color = TcColors.Text, fontSize = 14.sp)
    }
}

@Composable
private fun WeekStatusBadge(text: String) {
    Text(
        text = text,
        color = TcColors.Text,
        fontSize = 13.sp,
        fontWeight = FontWeight.Medium,
        modifier = Modifier
            .background(TcColors.Button, RoundedCornerShape(TcRadius.Medium))
            .border(1.dp, TcColors.ButtonBorder, RoundedCornerShape(TcRadius.Medium))
            .padding(horizontal = TcSpacing.Sm, vertical = 4.dp),
    )
}

@Composable
private fun RowScope.WeekCell(text: String, weight: Float, header: Boolean = false, strong: Boolean = false) {
    Text(
        text = text,
        color = if (header) TcColors.TextMuted else TcColors.Text,
        fontSize = if (header) 13.sp else 14.sp,
        fontWeight = if (header || strong) FontWeight.SemiBold else FontWeight.Normal,
        modifier = Modifier.weight(weight),
    )
}

@Composable
private fun RowScope.WeekMultilineCell(lines: List<String>, weight: Float) {
    Column(modifier = Modifier.weight(weight), verticalArrangement = Arrangement.spacedBy(4.dp)) {
        lines.ifEmpty { listOf("—") }.forEach {
            Text(it, color = TcColors.Text, fontSize = 14.sp)
        }
    }
}

private fun WeekDayDto.timeLines(): List<String> {
    val blocks = workBlocks
    return if (blocks.isNotEmpty()) {
        blocks.flatMapIndexed { index, block ->
            listOf("${if (blocks.size > 1) "Arbeitszeit ${index + 1}" else "Arbeitszeit"}: ${block.workTime ?: workTime ?: "—"}")
        }
    } else if (!workTime.isNullOrBlank()) {
        listOf("Arbeitszeit: $workTime")
    } else {
        emptyList()
    }
}

private fun WeekDayDto.workTotalLines(): List<String> {
    val lines = mutableListOf<String>()
    val blocks = workBlocks
    if (blocks.isNotEmpty()) {
        blocks.forEach { block -> lines.addAll(block.totalLines()) }
        if (blocks.size > 1 && !netWorkTime.isNullOrBlank()) lines.add("Gesamt: $netWorkTime")
    } else {
        totalWorkTime?.let { lines.add(it) }
        netWorkTime?.let { lines.add("= $it") }
    }
    holiday?.let { lines.add("+ ${it.hours.toHourLabel()}:00 ${it.description ?: "Feiertag"}") }
    vacation?.let { lines.add("+ ${it.hours.toHourLabel()}:00 Urlaub") }
    sick?.let { lines.add("${it.hours.toHourLabel()}:00 (${it.type.toSickLabel()})") }
    return lines
}

private fun WorkBlockDto.totalLines(): List<String> =
    buildList {
        totalWorkTime?.let { add(it) }
        netWorkTime?.let { add("= $it") }
    }

@Composable
private fun CalendarDemo(isTablet: Boolean) {
    if (isTablet) {
        Row(horizontalArrangement = Arrangement.spacedBy(TcSpacing.Xl), modifier = Modifier.fillMaxWidth()) {
            ListDemo(title = "Kalender", modifier = Modifier.weight(1f))
            TcCard(modifier = Modifier.weight(1f)) {
                SectionTitle("Tagesdetails")
                DetailRow("Datum", "14.05.2026")
                DetailRow("Typ", "Arbeitstag")
                DetailRow("Status", "Arbeit läuft")
            }
        }
    } else {
        ListDemo(title = "Kalender")
    }
}

@Composable
private fun FormDemo(title: String, primaryAction: String) {
    var text by remember(title) { mutableStateOf("") }
    TcCard {
        SectionTitle(title)
        TcTextField(label = "Bezeichnung", value = text, onValueChange = { text = it }, placeholder = "Eingabe")
        Row(horizontalArrangement = Arrangement.spacedBy(TcSpacing.Sm), modifier = Modifier.padding(top = TcSpacing.Lg)) {
            TcButton(primaryAction, variant = ButtonVariant.Primary)
            TcButton("Abbrechen")
        }
    }
}

@Composable
private fun ListDemo(title: String, modifier: Modifier = Modifier) {
    TcCard(modifier = modifier) {
        SectionTitle(title)
        DetailRow("Eintrag 1", "bereit")
        DetailRow("Eintrag 2", "offen")
        DetailRow("Eintrag 3", "geprüft")
    }
}

@Composable
private fun WeekCard(day: String, time: String, status: String) {
    TcCard {
        SectionTitle(day)
        DetailRow("Zeit", time)
        DetailRow("Status", status)
    }
}

private fun WeekOverviewDto.rangeText(): String =
    "${weekStart.toDisplayDate()} - ${weekEnd.toDisplayDate()}"

private fun String?.toDisplayDate(): String {
    if (this.isNullOrBlank()) return "—"
    return runCatching {
        LocalDate.parse(this.substring(0, 10)).format(DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY))
    }.recoverCatching {
        OffsetDateTime.parse(this).toLocalDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY))
    }.getOrDefault(this)
}

private fun Double.toHourLabel(): String =
    if (this % 1.0 == 0.0) toInt().toString() else toString()

private fun String?.toSickLabel(): String =
    when (this) {
        "self" -> "Krank"
        "child" -> "Kind krank"
        "parents" -> "Eltern krank"
        "partner" -> "Partner krank"
        null -> "Krank"
        else -> this
    }

@Composable
private fun SectionTitle(text: String) {
    Text(
        text = text,
        color = TcColors.Text,
        fontSize = 18.sp,
        fontWeight = FontWeight.SemiBold,
        modifier = Modifier.padding(bottom = TcSpacing.Md),
    )
}

@Composable
private fun DetailRow(label: String, value: String) {
    Row(modifier = Modifier.fillMaxWidth().padding(vertical = 3.dp), horizontalArrangement = Arrangement.SpaceBetween) {
        Text(text = "$label:", color = TcColors.TextMuted, fontSize = 14.sp)
        Text(text = value, color = TcColors.Text, fontSize = 14.sp)
    }
}
