package com.doctate.watch.presentation

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.foundation.lazy.items
import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState
import androidx.wear.compose.material3.Button
import androidx.wear.compose.material3.Card
import androidx.wear.compose.material3.EdgeButton
import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.ScreenScaffold
import androidx.wear.compose.material3.Text
import com.doctate.watch.DoctateApp
import com.doctate.watch.domain.CaseEntry
import com.doctate.watch.domain.displayText
import com.doctate.watch.domain.isManual

@Composable
fun CaseListScreen(
    onCaseTap: (caseId: String) -> Unit,
    onNewCase: () -> Unit,
) {
    val app = LocalContext.current.applicationContext as DoctateApp
    val cases by app.caseStore.casesFlow.collectAsStateWithLifecycle()
    val sync by app.syncStateProvider.state.collectAsStateWithLifecycle()
    val listState = rememberScalingLazyListState()

    // Display oldest-first so the newest entry sits next to the `Neu` EdgeButton.
    // Store invariant (lastActivityAt desc) stays untouched for Tile / Complication consumers.
    val displayed = cases.asReversed()

    // Scroll to the newest entry (now at the bottom) once data is available.
    LaunchedEffect(displayed.isNotEmpty()) {
        if (displayed.isNotEmpty()) {
            listState.scrollToItem(displayed.lastIndex)
        }
    }

    ScreenScaffold(
        scrollState = listState,
        edgeButton = {
            EdgeButton(onClick = onNewCase) {
                Text("● Neu")
            }
        },
        edgeButtonSpacing = 4.dp,
    ) { contentPadding ->
        if (displayed.isEmpty()) {
            EmptyState(onNewCase)
        } else {
            if (sync.queueLen > 0) {
                Text(
                    text = "☁↑${sync.queueLen}",
                    style = MaterialTheme.typography.bodyExtraSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 2.dp),
                    textAlign = TextAlign.Center,
                )
            }
            ScalingLazyColumn(
                state = listState,
                contentPadding = contentPadding,
                autoCentering = null,
                verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
                modifier = Modifier.fillMaxSize(),
            ) {
                items(displayed, key = { it.caseId }) { case ->
                    CaseRow(
                        case = case,
                        pendingUpload = case.caseId in sync.pendingCaseIds,
                        onTap = { onCaseTap(case.caseId) },
                    )
                }
            }
        }
    }
}

@Composable
private fun CaseRow(case: CaseEntry, pendingUpload: Boolean, onTap: () -> Unit) {
    Card(
        onClick = onTap,
        modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
        contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp),
    ) {
        Text(
            text = if (pendingUpload) "${formatTime(case.createdAt)} ↑" else formatTime(case.createdAt),
            style = MaterialTheme.typography.bodyExtraSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        )
        Text(
            text = formatOnelinerForRow(case),
            style = MaterialTheme.typography.bodySmall,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth().padding(top = 2.dp),
        )
    }
}

/** "👤 text" if doctor-authored, plain text if auto-generated, "…" placeholder otherwise. */
private fun formatOnelinerForRow(case: CaseEntry): String {
    val text = case.oneliner.displayText() ?: return "…"
    return if (case.oneliner.isManual()) "👤 $text" else text
}

@Composable
private fun EmptyState(onNewCase: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Text(
            "Noch keine Fälle heute",
            style = MaterialTheme.typography.titleMedium,
            textAlign = TextAlign.Center,
        )
        Button(
            onClick = onNewCase,
            modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
        ) {
            Text("● Neu")
        }
    }
}

