package com.syncflow.ui.conflict

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.hilt.navigation.compose.hiltViewModel
import com.syncflow.data.db.entities.SyncConflictEntity
import com.syncflow.domain.model.ConflictResolution
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConflictScreen(onBack: () -> Unit, vm: ConflictViewModel = hiltViewModel()) {
    val conflicts by vm.conflicts.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Conflicts (${conflicts.size})") },
                navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Default.ArrowBack, "Back") } },
                actions = {
                    if (conflicts.isNotEmpty()) {
                        var showMenu by remember { mutableStateOf(false) }
                        IconButton(onClick = { showMenu = true }) { Icon(Icons.Default.MoreVert, "Menu") }
                        DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
                            DropdownMenuItem(
                                text = { Text("Keep all local") },
                                onClick = { vm.resolveAll(ConflictResolution.KEEP_LOCAL); showMenu = false },
                            )
                            DropdownMenuItem(
                                text = { Text("Keep all remote") },
                                onClick = { vm.resolveAll(ConflictResolution.KEEP_REMOTE); showMenu = false },
                            )
                            DropdownMenuItem(
                                text = { Text("Keep both (rename)") },
                                onClick = { vm.resolveAll(ConflictResolution.KEEP_BOTH); showMenu = false },
                            )
                        }
                    }
                },
            )
        },
    ) { padding ->
        if (conflicts.isEmpty()) {
            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Icon(Icons.Default.CheckCircle, null, Modifier.size(64.dp), tint = MaterialTheme.colorScheme.primary)
                    Spacer(Modifier.height(12.dp))
                    Text("No conflicts!", style = MaterialTheme.typography.titleMedium)
                }
            }
        } else {
            LazyColumn(
                modifier = Modifier.padding(padding),
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                items(conflicts, key = { it.id }) { conflict ->
                    ConflictCard(conflict = conflict, onResolve = { vm.resolve(conflict, it) })
                }
            }
        }
    }
}

@Composable
private fun ConflictCard(conflict: SyncConflictEntity, onResolve: (ConflictResolution) -> Unit) {
    val fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
    val zone = ZoneId.systemDefault()

    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                conflict.relativePath,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.SemiBold,
            )
            Spacer(Modifier.height(10.dp))
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                VersionBox(
                    label = "Local",
                    modifiedAt = fmt.format(conflict.localModifiedAt.atZone(zone)),
                    size = conflict.localSizeBytes.formatBytes(),
                    icon = Icons.Default.PhoneAndroid,
                    modifier = Modifier.weight(1f),
                    color = MaterialTheme.colorScheme.primaryContainer,
                )
                Icon(Icons.Default.SwapHoriz, null, modifier = Modifier.align(Alignment.CenterVertically))
                VersionBox(
                    label = "Remote",
                    modifiedAt = fmt.format(conflict.remoteModifiedAt.atZone(zone)),
                    size = conflict.remoteSizeBytes.formatBytes(),
                    icon = Icons.Default.Cloud,
                    modifier = Modifier.weight(1f),
                    color = MaterialTheme.colorScheme.secondaryContainer,
                )
            }
            Spacer(Modifier.height(12.dp))
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedButton(onClick = { onResolve(ConflictResolution.KEEP_LOCAL) }, modifier = Modifier.weight(1f)) {
                    Text("Keep Local", style = MaterialTheme.typography.labelSmall)
                }
                OutlinedButton(onClick = { onResolve(ConflictResolution.KEEP_REMOTE) }, modifier = Modifier.weight(1f)) {
                    Text("Keep Remote", style = MaterialTheme.typography.labelSmall)
                }
                OutlinedButton(onClick = { onResolve(ConflictResolution.KEEP_BOTH) }, modifier = Modifier.weight(1f)) {
                    Text("Keep Both", style = MaterialTheme.typography.labelSmall)
                }
            }
        }
    }
}

@Composable
private fun VersionBox(label: String, modifiedAt: String, size: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier, color: androidx.compose.ui.graphics.Color) {
    Surface(modifier = modifier, shape = MaterialTheme.shapes.small, color = color) {
        Column(modifier = Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
            Icon(icon, null, Modifier.size(20.dp))
            Text(label, style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold)
            Text(modifiedAt, style = MaterialTheme.typography.labelSmall)
            Text(size, style = MaterialTheme.typography.labelSmall)
        }
    }
}

private fun Long.formatBytes(): String = when {
    this < 1024 -> "${this}B"
    this < 1024 * 1024 -> "${"%.1f".format(this / 1024.0)}KB"
    this < 1024 * 1024 * 1024 -> "${"%.1f".format(this / 1024.0 / 1024)}MB"
    else -> "${"%.1f".format(this / 1024.0 / 1024 / 1024)}GB"
}
