package de.tsschulz.timeclock.ui.time

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.ui.Alignment
import androidx.compose.ui.Modifier
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.TimeEntryDto
import de.tsschulz.timeclock.data.api.TimeStatsDto
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.model.ButtonVariant
import de.tsschulz.timeclock.ui.theme.TcColors
import de.tsschulz.timeclock.ui.theme.TcRadius
import de.tsschulz.timeclock.ui.theme.TcSpacing
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

@Composable
fun EntriesScreen(
    entries: List<TimeEntryDto>,
    loading: Boolean,
    error: String?,
    onRefresh: () -> Unit,
    onDelete: (String) -> Unit,
) {
    TcCard {
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
            SectionTitle("${entries.size} Einträge")
            TcButton("Aktualisieren", variant = ButtonVariant.Secondary, onClick = onRefresh)
        }
    }
    if (loading) TcLoading("Lade Einträge...")
    error?.let { TcError(it) }
    if (!loading && entries.isEmpty()) {
        TcCard { Text("Keine Einträge vorhanden.", color = TcColors.TextMuted, fontSize = 14.sp) }
    } else {
        entries.forEach { entry -> EntryRow(entry, onDelete) }
    }
}

@Composable
fun StatsScreen(
    stats: TimeStatsDto?,
    loading: Boolean,
    error: String?,
    onRefresh: () -> Unit,
) {
    TcCard {
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
            SectionTitle("Statistiken")
            TcButton("Aktualisieren", variant = ButtonVariant.Secondary, onClick = onRefresh)
        }
    }
    if (loading) TcLoading("Lade Statistiken...")
    error?.let { TcError(it) }
    val data = stats
    if (data == null && !loading) {
        TcCard { Text("Keine Statistiken vorhanden.", color = TcColors.TextMuted, fontSize = 14.sp) }
        return
    }
    data?.let {
        Row(horizontalArrangement = Arrangement.spacedBy(TcSpacing.Lg), modifier = Modifier.fillMaxWidth()) {
            StatCard("Arbeitszeit heute", it.currentlyWorked ?: "-", Modifier.weight(1f))
            StatCard("Offen heute", it.open ?: "-", Modifier.weight(1f))
        }
        Row(horizontalArrangement = Arrangement.spacedBy(TcSpacing.Lg), modifier = Modifier.fillMaxWidth()) {
            StatCard("Woche", it.weekWorktime ?: "-", Modifier.weight(1f))
            StatCard("Überstunden", it.totalOvertime ?: it.overtime ?: "-", Modifier.weight(1f))
        }
        TcCard {
            Detail("Reguläres Ende", it.regularEnd ?: "-")
            Detail("Angepasstes Ende", it.adjustedEndTodayGeneral ?: it.adjustedEndToday ?: "-")
            Detail("Fehlende Pause", it.missingBreakMinutes?.let { minutes -> "$minutes min" } ?: "-")
            Detail("Nicht-Arbeitszeit", it.nonWorkingHours ?: "-")
        }
    }
}

@Composable
private fun EntryRow(entry: TimeEntryDto, onDelete: (String) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(TcColors.Background, RoundedCornerShape(TcRadius.Medium))
            .border(1.dp, TcColors.Border, RoundedCornerShape(TcRadius.Medium))
            .padding(TcSpacing.Md),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(TcSpacing.Md),
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(entry.project ?: "Allgemein", color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
            Text(
                "${entry.startTime.toDisplayDateTime()} - ${entry.endTime.toDisplayDateTime()} · ${entry.duration.toDurationText()}",
                color = TcColors.TextMuted,
                fontSize = 13.sp,
            )
            if (!entry.description.isNullOrBlank()) Text(entry.description, color = TcColors.TextMuted, fontSize = 13.sp)
        }
        Text(if (entry.isRunning) "Läuft" else "Beendet", color = if (entry.isRunning) TcColors.Danger else TcColors.Success, fontSize = 13.sp)
        TcButton("Löschen", variant = ButtonVariant.Danger, onClick = { onDelete(entry.id) })
    }
}

@Composable
private fun StatCard(label: String, value: String, modifier: Modifier = Modifier) {
    TcCard(modifier = modifier) {
        Text(value, color = TcColors.Text, fontSize = 22.sp, fontWeight = FontWeight.Bold)
        Text(label, color = TcColors.TextMuted, fontSize = 13.sp)
    }
}

@Composable
private fun SectionTitle(title: String) {
    Text(title, color = TcColors.Text, fontSize = 18.sp, fontWeight = FontWeight.SemiBold)
}

@Composable
private fun Detail(label: String, value: String) {
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
        Text(label, color = TcColors.TextMuted, fontSize = 14.sp)
        Text(value, color = TcColors.Text, fontSize = 14.sp, fontWeight = FontWeight.Medium)
    }
}

private fun String?.toDisplayDateTime(): String {
    if (this.isNullOrBlank()) return "-"
    return runCatching {
        OffsetDateTime.parse(this).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm", Locale.GERMANY))
    }.getOrDefault(this)
}

private fun Long?.toDurationText(): String {
    if (this == null) return "-"
    val hours = this / 3600
    val minutes = (this % 3600) / 60
    val seconds = this % 60
    return "%02d:%02d:%02d".format(hours, minutes, seconds)
}
