package app.voltplan.cable.ui.loads

import androidx.compose.foundation.horizontalScroll
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Bolt
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.LibraryBooks
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.voltplan.cable.R
import app.voltplan.cable.data.UnitSystem
import app.voltplan.cable.data.model.SavedLoad
import app.voltplan.cable.ui.components.LoadIcon
import app.voltplan.cable.ui.components.MetricBadge
import app.voltplan.cable.ui.components.StatsHeader
import app.voltplan.cable.ui.components.StatusBanner
import app.voltplan.cable.ui.components.SummaryMetric
import app.voltplan.cable.ui.system.DetailState
import app.voltplan.cable.ui.theme.SysGreen
import app.voltplan.cable.ui.theme.SysOrange
import app.voltplan.cable.ui.theme.SysPink
import app.voltplan.cable.ui.theme.SysTeal
import app.voltplan.cable.ui.theme.componentColor
import app.voltplan.cable.util.Fmt

@Composable
fun ComponentsTab(
    state: DetailState,
    unitSystem: UnitSystem,
    onOpenLoad: (String) -> Unit,
    onNewLoad: () -> Unit,
    onOpenLibrary: () -> Unit,
    onDeleteLoad: (SavedLoad) -> Unit,
) {
    val loads = state.loads
    if (loads.isEmpty()) {
        app.voltplan.cable.ui.components.OnboardingInfo(
            icon = Icons.Outlined.Layers,
            title = stringResource(R.string.loads_onboarding_title),
            subtitle = stringResource(R.string.loads_onboarding_subtitle),
            primaryLabel = stringResource(R.string.loads_empty_create),
            onPrimary = onNewLoad,
            secondaryLabel = stringResource(R.string.loads_empty_library),
            onSecondary = onOpenLibrary,
        )
        return
    }

    Box(Modifier.fillMaxSize()) {
        Column(Modifier.fillMaxSize()) {
            StatsHeader {
                Text(
                    stringResource(R.string.loads_overview_header_title),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                )
                Row(
                    Modifier.fillMaxWidth().padding(top = 12.dp).horizontalScroll(rememberScrollState()),
                    horizontalArrangement = Arrangement.spacedBy(20.dp),
                ) {
                    SummaryMetric(Icons.Outlined.Layers, loads.size.toString(), stringResource(R.string.loads_metric_count), MaterialTheme.colorScheme.primary)
                    SummaryMetric(Icons.Outlined.Bolt, "${Fmt.number(state.metrics.totalCurrent)} A", stringResource(R.string.loads_metric_current), SysOrange)
                    SummaryMetric(Icons.Outlined.Speed, "${Fmt.number(state.metrics.totalPower)} W", stringResource(R.string.loads_metric_power), SysGreen)
                }
                val missing = state.metrics.loadsMissingDetails
                if (missing > 0) {
                    Box(Modifier.padding(top = 12.dp)) {
                        StatusBanner(
                            symbol = Icons.Outlined.Warning,
                            text = stringResource(R.string.loads_status_missing_banner),
                            tint = SysOrange,
                        )
                    }
                }
            }

            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 96.dp),
            ) {
                items(loads, key = { it.id }) { load ->
                    LoadRow(load, unitSystem, onClick = { onOpenLoad(load.id) }, onDelete = { onDeleteLoad(load) })
                }
            }
        }

        ExtendedFloatingActionButton(
            onClick = onOpenLibrary,
            icon = { Icon(Icons.Outlined.LibraryBooks, contentDescription = null) },
            text = { Text(stringResource(R.string.loads_library_button)) },
            modifier = Modifier.align(Alignment.BottomEnd).padding(24.dp),
        )
    }
}

@Composable
private fun LoadRow(load: SavedLoad, unit: UnitSystem, onClick: () -> Unit, onDelete: () -> Unit) {
    Surface(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp).clip(RoundedCornerShape(18.dp)),
        color = MaterialTheme.colorScheme.surface,
        tonalElevation = 1.dp,
        onClick = onClick,
    ) {
        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                LoadIcon(load.remoteIconURLString, load.iconName, componentColor(load.colorName), 48.dp)
                Column(Modifier.weight(1f)) {
                    Text(load.name, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyLarge)
                    Text(
                        LoadFormatting.summaryBadge(load, unit),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                    )
                }
                IconButton(onClick = onDelete) {
                    Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.action_delete), tint = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                MetricBadge(stringResource(R.string.loads_metric_fuse), LoadFormatting.fuseString(load), SysPink, Modifier.weight(1f))
                MetricBadge(stringResource(R.string.loads_metric_cable), LoadFormatting.wireGaugeString(load, unit), SysTeal, Modifier.weight(1f))
                MetricBadge(stringResource(R.string.loads_metric_length), LoadFormatting.lengthString(load, unit), SysOrange, Modifier.weight(1f))
            }
        }
    }
}
