package com.a2i.forwarder.ui.screens

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
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.unit.dp
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.core.UpdateInfo
import kotlinx.coroutines.launch
import java.io.File
import java.util.Locale

@Composable
fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) {
    val app = A2iApp.instance
    val downloading by app.updateChecker.downloading.collectAsState()
    val progress by app.updateChecker.downloadProgress.collectAsState()
    var downloadedFile by remember { mutableStateOf<File?>(null) }

    AlertDialog(
        onDismissRequest = { if (!downloading) onDismiss() },
        title = { Text("发现新版本 v${info.latestVersion}") },
        text = {
            Column {
                Text(
                    "安装包大小：${formatSize(info.apkSize)}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                Spacer(Modifier.size(8.dp))
                Column(
                    modifier = Modifier
                        .heightIn(max = 240.dp)
                        .verticalScroll(rememberScrollState()),
                ) {
                    val notes = info.releaseNotes.ifBlank { "（作者未提供更新说明）" }
                    Text(notes, style = MaterialTheme.typography.bodyMedium)
                }
                if (downloading) {
                    Spacer(Modifier.size(12.dp))
                    LinearProgressIndicator(
                        progress = { progress / 100f },
                        modifier = Modifier.fillMaxWidth(),
                    )
                    Spacer(Modifier.size(4.dp))
                    Text(
                        "$progress%",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
                downloadedFile?.let {
                    Spacer(Modifier.size(8.dp))
                    Text(
                        "下载完成，点击「安装」继续",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.tertiary,
                    )
                }
            }
        },
        confirmButton = {
            if (downloadedFile == null) {
                Button(
                    onClick = {
                        app.appScope.launch {
                            val f = app.updateChecker.download(info)
                            if (f != null) downloadedFile = f
                        }
                    },
                    enabled = !downloading,
                ) {
                    if (downloading) {
                        CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
                    } else {
                        Text("下载并安装")
                    }
                }
            } else {
                Button(onClick = { app.updateChecker.install(downloadedFile!!) }) { Text("安装") }
            }
        },
        dismissButton = {
            Row {
                TextButton(
                    onClick = { app.updateChecker.ignoreVersion(info.latestVersion); onDismiss() },
                    enabled = !downloading,
                ) { Text("忽略此版本") }
                TextButton(onClick = onDismiss, enabled = !downloading) { Text("稍后") }
            }
        },
    )
}

fun formatSize(bytes: Long): String {
    if (bytes <= 0) return "未知"
    val kb = bytes / 1024.0
    return if (kb >= 1024) String.format(Locale.US, "%.1f MB", kb / 1024) else String.format(Locale.US, "%.0f KB", kb)
}
