package app.voltplan.cable.ui.batteries

import androidx.compose.foundation.background
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.layout.size
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.BatteryChargingFull
import androidx.compose.material.icons.outlined.BatteryFull
import androidx.compose.material.icons.outlined.Bolt
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Warning
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.graphics.Color
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.calc.BankWarning
import app.voltplan.cable.data.model.SavedBattery
import app.voltplan.cable.data.model.chemistry
import app.voltplan.cable.data.model.energyWattHours
import app.voltplan.cable.data.model.usableCapacityAmpHours
import app.voltplan.cable.data.model.usableCapacityFraction
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.sfSymbol
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.SysOrange
import app.voltplan.cable.ui.theme.SysPurple
import app.voltplan.cable.ui.theme.SysRed
import app.voltplan.cable.ui.theme.componentColor
import app.voltplan.cable.util.Fmt
import java.util.Locale
import kotlin.math.roundToInt

@Composable
fun BatteriesTab(
    state: DetailState,
    onEditBattery: (String) -> Unit,
    onNewBattery: () -> Unit,
    onDeleteBattery: (SavedBattery) -> Unit,
) {
    val batteries = state.batteries
    if (batteries.isEmpty()) {
        app.voltplan.cable.ui.components.OnboardingInfo(
            icon = Icons.Outlined.BatteryFull,
            title = stringResource(R.string.battery_onboarding_title),
            subtitle = stringResource(R.string.battery_onboarding_subtitle),
            primaryLabel = stringResource(R.string.battery_empty_create),
            onPrimary = onNewBattery,
        )
        return
    }

    val m = state.metrics
    Column(Modifier.fillMaxSize()) {
        StatsHeader {
            Text(stringResource(R.string.battery_bank_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.BatteryFull, batteries.size.toString(), stringResource(R.string.battery_metric_count), SysBlue)
                SummaryMetric(Icons.Outlined.Speed, "${Fmt.number(m.totalCapacity)} Ah", stringResource(R.string.battery_metric_capacity), SysOrange)
                SummaryMetric(Icons.Outlined.BatteryChargingFull, "${Fmt.number(m.totalUsableCapacity)} Ah", stringResource(R.string.battery_metric_usable_capacity), SysPurple)
                SummaryMetric(Icons.Outlined.Bolt, "${Fmt.number(m.totalUsableEnergy)} Wh", stringResource(R.string.battery_metric_usable_energy), SysGreen)
            }
            when (val w = m.bankWarning) {
                is BankWarning.Voltage -> Box(Modifier.padding(top = 12.dp)) {
                    StatusBanner(Icons.Outlined.Warning, stringResource(R.string.battery_banner_voltage), SysRed)
                }
                is BankWarning.Capacity -> Box(Modifier.padding(top = 12.dp)) {
                    StatusBanner(Icons.Outlined.Warning, stringResource(R.string.battery_banner_capacity), SysOrange)
                }
                null -> {}
            }
        }

        LazyColumn(Modifier.fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 24.dp)) {
            items(batteries, key = { it.id }) { battery ->
                BatteryRow(battery, onClick = { onEditBattery(battery.id) }, onDelete = { onDeleteBattery(battery) })
            }
        }
    }
}

@Composable
private fun BatteryRow(battery: SavedBattery, 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)) {
                Box(
                    Modifier.size(48.dp).clip(RoundedCornerShape(12.dp)).background(componentColor(battery.colorName)),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(sfSymbol(battery.iconName.ifBlank { "battery.100.bolt" }), contentDescription = null, tint = Color.White, modifier = Modifier.size(22.dp))
                }
                Column(Modifier.weight(1f)) {
                    Text(battery.name, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
                    Text(battery.chemistry.displayName, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
                Text(String.format(Locale.US, "%.1f V", battery.nominalVoltage), style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                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.battery_badge_voltage), String.format(Locale.US, "%.1f V", battery.nominalVoltage), SysOrange)
                MetricBadge(stringResource(R.string.battery_metric_capacity), String.format(Locale.US, "%.1f Ah", battery.capacityAmpHours), SysBlue)
                MetricBadge(
                    stringResource(R.string.battery_metric_usable_capacity),
                    String.format(Locale.US, "%.1f Ah (%d%%)", battery.usableCapacityAmpHours, (battery.usableCapacityFraction * 100).roundToInt()),
                    SysPurple,
                )
                MetricBadge(stringResource(R.string.battery_badge_energy), String.format(Locale.US, "%.1f Wh", battery.energyWattHours), SysGreen)
            }
        }
    }
}
