package app.voltplan.cable.ui.chargers

import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
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.BatteryChargingFull
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Speed
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.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.model.SavedCharger
import app.voltplan.cable.data.model.effectivePowerWatts
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.SummaryMetric
import app.voltplan.cable.ui.system.DetailState
import app.voltplan.cable.ui.theme.SysBlue
import app.voltplan.cable.ui.theme.SysGreen
import app.voltplan.cable.ui.theme.SysIndigo
import app.voltplan.cable.ui.theme.SysOrange
import app.voltplan.cable.ui.theme.SysPink
import app.voltplan.cable.ui.theme.componentColor
import app.voltplan.cable.util.Fmt
import java.util.Locale

private fun v(value: Double) = if (value > 0) String.format(Locale.US, "%.1f V", value) else "—"
private fun a(value: Double) = if (value > 0) String.format(Locale.US, "%.1f A", value) else "—"
private fun w(value: Double) = if (value > 0) String.format(Locale.US, "%.0f W", value) else "—"

@Composable
fun ChargersTab(
    state: DetailState,
    onEditCharger: (String) -> Unit,
    onNewCharger: () -> Unit,
    onDeleteCharger: (SavedCharger) -> Unit,
) {
    val chargers = state.chargers
    if (chargers.isEmpty()) {
        app.voltplan.cable.ui.components.OnboardingInfo(
            icon = Icons.Outlined.Bolt,
            title = stringResource(R.string.chargers_onboarding_title),
            subtitle = stringResource(R.string.chargers_onboarding_subtitle),
            primaryLabel = stringResource(R.string.chargers_onboarding_primary),
            onPrimary = onNewCharger,
        )
        return
    }

    val m = state.metrics
    Column(Modifier.fillMaxSize()) {
        StatsHeader {
            Text(stringResource(R.string.chargers_summary_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.Bolt, chargers.size.toString(), stringResource(R.string.chargers_metric_count), SysBlue)
                m.representativeChargerOutput?.let {
                    SummaryMetric(Icons.Outlined.BatteryChargingFull, String.format(Locale.US, "%.1f V", it), stringResource(R.string.chargers_metric_output), SysGreen)
                }
                SummaryMetric(Icons.Outlined.Speed, "${Fmt.number(m.totalChargerCurrent)} A", stringResource(R.string.chargers_metric_current), SysOrange)
                SummaryMetric(Icons.Outlined.Bolt, "${Fmt.number(m.totalChargerPower)} W", stringResource(R.string.chargers_metric_power), SysPink)
            }
        }
        LazyColumn(Modifier.fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 24.dp)) {
            items(chargers, key = { it.id }) { charger ->
                ChargerRow(charger, onClick = { onEditCharger(charger.id) }, onDelete = { onDeleteCharger(charger) })
            }
        }
    }
}

@Composable
private fun ChargerRow(charger: SavedCharger, 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(14.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                LoadIcon(charger.remoteIconURLString, charger.iconName, componentColor(charger.colorName), 48.dp)
                Column(Modifier.weight(1f)) {
                    Text(charger.name, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
                    Text(
                        "${v(charger.inputVoltage)} • ${v(charger.outputVoltage)} • ${a(charger.maxCurrentAmps)}",
                        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(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                MetricBadge(stringResource(R.string.chargers_badge_input), v(charger.inputVoltage), SysIndigo)
                MetricBadge(stringResource(R.string.chargers_badge_output), v(charger.outputVoltage), SysGreen)
                MetricBadge(stringResource(R.string.chargers_badge_current), a(charger.maxCurrentAmps), SysOrange)
                MetricBadge(stringResource(R.string.chargers_badge_power), w(charger.effectivePowerWatts), SysPink)
            }
        }
    }
}
