package app.voltplan.cable.ui.systems

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ChevronRight
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
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.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import app.voltplan.cable.R
import app.voltplan.cable.ui.sfSymbol
import app.voltplan.cable.ui.theme.componentColor

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SystemsScreen(
    onOpenSystem: (String) -> Unit,
    onOpenSettings: () -> Unit,
    onOpenLibrary: () -> Unit,
    vm: SystemsViewModel = viewModel(),
) {
    val summaries by vm.systems.collectAsStateWithLifecycle()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.systems_title)) },
                navigationIcon = {
                    IconButton(onClick = { Analytics_settings(onOpenSettings) }) {
                        Icon(Icons.Outlined.Settings, contentDescription = stringResource(R.string.settings_title))
                    }
                },
                actions = {
                    IconButton(onClick = {
                        vm.logCreateNavigation()
                        vm.createSystem(null, source = "toolbar", randomColor = false, onCreated = onOpenSystem)
                    }) {
                        Icon(Icons.Outlined.Add, contentDescription = stringResource(R.string.action_add))
                    }
                },
            )
        },
    ) { padding ->
        if (summaries.isEmpty()) {
            SystemsOnboarding(
                modifier = Modifier.padding(padding),
                onCreate = { name ->
                    vm.createSystem(name, source = "onboarding", randomColor = true, onCreated = onOpenSystem)
                },
            )
        } else {
            LazyColumn(
                modifier = Modifier.padding(padding).fillMaxSize(),
                contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),
            ) {
                items(summaries, key = { it.system.id }) { summary ->
                    SystemRow(
                        summary = summary,
                        onClick = {
                            vm.logOpen(summary, "list")
                            onOpenSystem(summary.system.id)
                        },
                        onDelete = { vm.deleteSystem(summary) },
                    )
                }
            }
        }
    }
}

private fun Analytics_settings(onOpenSettings: () -> Unit) {
    app.voltplan.cable.analytics.Analytics.log("Settings Opened")
    onOpenSettings()
}

@Composable
private fun SystemRow(summary: SystemSummary, onClick: () -> Unit, onDelete: () -> Unit) {
    val system = summary.system
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 6.dp)
            .clip(RoundedCornerShape(18.dp)),
        color = MaterialTheme.colorScheme.surface,
        tonalElevation = 1.dp,
        onClick = onClick,
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Box(
                Modifier.size(44.dp).clip(RoundedCornerShape(10.dp)).background(componentColor(system.colorName)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(sfSymbol(system.iconName), contentDescription = null, tint = Color.White, modifier = Modifier.size(24.dp))
            }
            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(system.name, fontWeight = FontWeight.Medium, style = MaterialTheme.typography.bodyLarge)
                if (system.location.isNotEmpty()) {
                    Text(system.location, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
                Text(
                    componentSummaryText(summary),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
            IconButton(onClick = onDelete) {
                Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.action_delete), tint = MaterialTheme.colorScheme.onSurfaceVariant)
            }
            Icon(Icons.Outlined.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }
}

@Composable
private fun componentSummaryText(summary: SystemSummary): String {
    if (summary.loadCount == 0) return stringResource(R.string.system_list_no_components)
    val count = pluralStringResource(R.plurals.component_count, summary.loadCount, summary.loadCount)
    return "$count • ${summaryPowerLabel(summary.totalPower)}"
}

@Composable
private fun SystemsOnboarding(modifier: Modifier = Modifier, onCreate: (String) -> Unit) {
    var name by rememberSaveable { mutableStateOf("") }
    val defaultName = stringResource(R.string.default_system_name)
    val effective = remember(name) { name }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f))
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Icon(Icons.Outlined.AutoAwesome, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(48.dp))
        Spacer(Modifier.size(16.dp))
        Text(stringResource(R.string.onboarding_systems_title), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold)
        Spacer(Modifier.size(8.dp))
        Text(
            stringResource(R.string.onboarding_systems_subtitle),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        Spacer(Modifier.size(24.dp))
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(stringResource(R.string.onboarding_systems_field)) },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
        )
        Spacer(Modifier.size(16.dp))
        Button(
            onClick = { onCreate(effective.ifBlank { defaultName }) },
            modifier = Modifier.fillMaxWidth(),
        ) {
            Icon(Icons.Outlined.Add, contentDescription = null, modifier = Modifier.size(18.dp))
            Spacer(Modifier.size(8.dp))
            Text(stringResource(R.string.onboarding_systems_create), fontWeight = FontWeight.SemiBold)
        }
    }
}
