package com.github.nullptroma.wallenc.ui.screens.main.screens.tasks

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.github.nullptroma.wallenc.domain.tasks.PipelineTask
import com.github.nullptroma.wallenc.domain.tasks.TaskLogLevel
import com.github.nullptroma.wallenc.domain.tasks.TaskRunState
import com.github.nullptroma.wallenc.ui.R
import com.github.nullptroma.wallenc.domain.tasks.TaskLogLine
import com.github.nullptroma.wallenc.ui.resources.displayText
import com.github.nullptroma.wallenc.ui.resources.formatTaskPipelineTime
import com.github.nullptroma.wallenc.ui.resources.resolveText
import com.github.nullptroma.wallenc.ui.resources.toUserNotification

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskPipelineScreen(
    modifier: Modifier = Modifier,
    viewModel: TaskPipelineViewModel = hiltViewModel(),
) {
    val pipeline by viewModel.orchestrator.pipelineState.collectAsStateWithLifecycle()
    val logs by viewModel.orchestrator.logLines.collectAsStateWithLifecycle()
    val hasAnyTask = pipeline.tasks.isNotEmpty()
    val runningTaskIds = pipeline.runningTaskIds
    var showTestDialog by remember { mutableStateOf(false) }
    var testDurationSec by remember { mutableFloatStateOf(10f) }
    var testInfinity by remember { mutableStateOf(false) }

    Scaffold(
        modifier = modifier,
        topBar = {
            TopAppBar(
                windowInsets = WindowInsets(0.dp),
                title = { Text(stringResource(R.string.task_pipeline_title)) },
            )
        },
    ) { inner ->
        Column(
            Modifier
                .padding(inner)
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text(
                stringResource(R.string.task_pipeline_jobs),
                style = MaterialTheme.typography.titleMedium,
            )
            LazyColumn(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                items(pipeline.tasks, key = { it.id.uuid }) { task ->
                    TaskRow(task = task, isRunning = task.id in runningTaskIds)
                }
            }
            Text(
                stringResource(R.string.task_pipeline_log),
                style = MaterialTheme.typography.titleMedium,
            )
            LazyColumn(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp),
            ) {
                items(logs.size) { i ->
                    PipelineLogRow(line = logs[i])
                }
            }
            Button(
                onClick = { showTestDialog = true },
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text(stringResource(R.string.task_pipeline_run_test))
            }

            Button(
                onClick = { viewModel.orchestrator.cancelAll() },
                enabled = hasAnyTask,
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text(stringResource(R.string.task_pipeline_cancel_all))
            }
        }
    }

    if (showTestDialog) {
        AlertDialog(
            onDismissRequest = { showTestDialog = false },
            title = { Text(stringResource(R.string.task_pipeline_test_dialog_title)) },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Text(
                        stringResource(
                            R.string.task_pipeline_test_dialog_duration,
                            testDurationSec.toInt(),
                        )
                    )
                    Slider(
                        value = testDurationSec,
                        onValueChange = { testDurationSec = it },
                        valueRange = 0f..60f,
                    )
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        Checkbox(
                            checked = testInfinity,
                            onCheckedChange = { testInfinity = it },
                        )
                        Text(
                            stringResource(R.string.task_pipeline_test_dialog_infinity),
                            modifier = Modifier
                                .clickable { testInfinity = !testInfinity }
                                .weight(1f),
                        )
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        viewModel.startTestTask(
                            testDurationSec.toInt(),
                            testInfinity,
                        )
                        showTestDialog = false
                    },
                ) {
                    Text(stringResource(R.string.task_pipeline_test_dialog_start))
                }
            },
            dismissButton = {
                Button(onClick = { showTestDialog = false }) {
                    Text(stringResource(R.string.task_pipeline_test_dialog_cancel))
                }
            },
        )
    }
}

@Composable
private fun PipelineLogRow(line: TaskLogLine) {
    val prefix = when (line.level) {
        TaskLogLevel.Debug -> "D"
        TaskLogLevel.Info -> "I"
        TaskLogLevel.Warn -> "W"
        TaskLogLevel.Error -> "E"
    }
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.Top,
    ) {
        Text(
            text = "[$prefix] ${line.displayText()}",
            modifier = Modifier
                .weight(1f)
                .padding(end = 8.dp),
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        Text(
            text = formatTaskPipelineTime(line.timestampMs),
            modifier = Modifier.widthIn(min = 56.dp),
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
    }
}

@Composable
private fun TaskRow(task: PipelineTask, isRunning: Boolean) {
    Column(Modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = task.title,
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 8.dp),
                style = if (isRunning) MaterialTheme.typography.titleSmall
                else MaterialTheme.typography.bodyMedium,
            )
            Text(
                text = formatTaskPipelineTime(task.enqueuedAtMs),
                modifier = Modifier.widthIn(min = 56.dp),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
        val runningProgress = (task.state as? TaskRunState.Running)?.progress
        val progressLabel = runningProgress?.label?.resolveText()
        val stateLabel = when (val s = task.state) {
            TaskRunState.Queued -> stringResource(R.string.task_state_queued)
            is TaskRunState.Running ->
                progressLabel ?: stringResource(R.string.task_state_running)
            TaskRunState.Completed -> stringResource(R.string.task_state_completed)
            TaskRunState.Cancelled -> stringResource(R.string.task_state_cancelled)
            is TaskRunState.Failed -> {
                val notification = s.error.toUserNotification()
                stringResource(
                    R.string.task_state_failed,
                    if (notification.formatArgs.isEmpty()) {
                        stringResource(notification.id)
                    } else {
                        stringResource(notification.id, *notification.formatArgs.toTypedArray())
                    },
                )
            }
        }
        Text(stateLabel, style = MaterialTheme.typography.bodySmall)
        if (task.state is TaskRunState.Running) {
            val frac = runningProgress?.fraction
            if (frac != null) {
                LinearProgressIndicator(
                    progress = { frac },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp),
                )
            } else {
                LinearProgressIndicator(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp),
                )
            }
        }
    }
}
