package net.sergeych.toread

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material.icons.filled.Scanner
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun ScanScreen(
    state: AppState.Scan,
    activeScan: LibraryScanProgress?,
    onStateChange: (AppState) -> Unit,
    onStartScan: (String) -> Unit,
) {
    val scope = rememberCoroutineScope()
    var scanPath by remember(state.scanPath) { mutableStateOf(state.scanPath) }
    var message by remember(state.message) { mutableStateOf(state.message) }
    val busy = activeScan != null

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text(strings.scan) },
                navigationIcon = {
                    IconButton(onClick = { onStateChange(AppState.Library(state.items, scanPath, message, state.selectedFilter)) }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.backToLibrary)
                    }
                },
                colors = themedTopAppBarColors(),
            )
        },
    ) {
        BoxWithConstraints(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .background(readerBackground()),
        ) {
            val wide = maxWidth >= 800.dp
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(if (wide) 24.dp else 14.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp),
            ) {
                Card(shape = RoundedCornerShape(8.dp), colors = quietCardColors(), modifier = Modifier.fillMaxWidth()) {
                    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                        OutlinedTextField(
                            value = scanPath,
                            onValueChange = { scanPath = it },
                            label = { Text(strings.rootFolder) },
                            singleLine = true,
                            modifier = Modifier.fillMaxWidth(),
                        )
                        Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
                            Button(
                                onClick = {
                                    message = strings.scanning
                                    onStartScan(scanPath)
                                },
                                enabled = !busy && scanPath.isNotBlank(),
                            ) {
                                Icon(Icons.Filled.Scanner, contentDescription = null)
                                Spacer(Modifier.width(8.dp))
                                Text(strings.scan)
                            }
                            FilledTonalButton(
                                onClick = {
                                    scope.launch {
                                        chooseLibraryScanDirectory()?.let { scanPath = it }
                                    }
                                },
                                enabled = !busy,
                            ) {
                                Icon(Icons.Filled.FolderOpen, contentDescription = null)
                                Spacer(Modifier.width(8.dp))
                                Text(strings.choose)
                            }
                            if (busy) {
                                CircularProgressIndicator(modifier = Modifier.width(24.dp).height(24.dp), strokeWidth = 2.dp)
                            }
                        }
                        if (activeScan != null) {
                            Text(
                                activeScan.toScanMessage(),
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.primary,
                            )
                        }
                        message?.let {
                            Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
                        }
                        libraryLogPath()?.let {
                            Text("${strings.logPrefix}: $it", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
                        }
                    }
                }
            }
        }
    }
}

private fun LibraryScanProgress.toScanMessage(): String =
    strings.checkingFile(currentFile, scannedFiles, importedFiles, skippedFiles, failedFiles)
