package app.voltplan.cable.ui.overview

import androidx.compose.foundation.clickable
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.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BatteryFull
import androidx.compose.material.icons.outlined.Bolt
import androidx.compose.material.icons.outlined.ListAlt
import androidx.compose.material.icons.outlined.Schedule
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.voltplan.cable.R
import app.voltplan.cable.calc.SystemMetrics
import app.voltplan.cable.calc.formatDurationHours
import app.voltplan.cable.data.UnitSystem
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.SysOrange
import app.voltplan.cable.ui.theme.SysPurple
import app.voltplan.cable.util.Fmt

@Composable
fun OverviewTab(
    state: DetailState,
    unitSystem: UnitSystem,
    onAddLoad: () -> Unit,
    onAddBattery: () -> Unit,
    onAddCharger: () -> Unit,
    onOpenLibrary: () -> Unit,
    onOpenBom: () -> Unit,
    onSetRuntimeGoal: (Double?) -> Unit,
    onSetChargeGoal: (Double?) -> Unit,
) {
    val m = state.metrics
    val system = state.system
    var goalEditor by remember { mutableStateOf<GoalKind?>(null) }

    Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
        StatsHeader {
            Text(stringResource(R.string.overview_system_header_title), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            Column(Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
                MetricRow(
                    icon = Icons.Outlined.Schedule,
                    tint = SysOrange,
                    title = stringResource(R.string.overview_runtime_title),
                    subtitle = stringResource(R.string.overview_runtime_subtitle),
                    value = m.estimatedRuntimeHours?.let { formatDurationHours(it) }
                        ?: if (state.batteries.isEmpty() || state.loads.isEmpty()) stringResource(R.string.overview_runtime_placeholder) else "—",
                    goalHours = system?.targetRuntimeHours,
                    progress = goalProgress(m.estimatedRuntimeHours, system?.targetRuntimeHours, charge = false),
                    onClick = { goalEditor = GoalKind.RUNTIME },
                )
                MetricRow(
                    icon = Icons.Outlined.Bolt,
                    tint = SysBlue,
                    title = stringResource(R.string.overview_chargetime_title),
                    subtitle = stringResource(R.string.overview_chargetime_subtitle),
                    value = m.estimatedChargeHours?.let { formatDurationHours(it) }
                        ?: if (state.chargers.isEmpty()) stringResource(R.string.overview_chargetime_placeholder) else "—",
                    goalHours = system?.targetChargeTimeHours,
                    progress = goalProgress(m.estimatedChargeHours, system?.targetChargeTimeHours, charge = true),
                    onClick = { goalEditor = GoalKind.CHARGE },
                )
                MetricRow(
                    icon = Icons.Outlined.ListAlt,
                    tint = SysPurple,
                    title = stringResource(R.string.overview_bom_title),
                    subtitle = stringResource(R.string.overview_bom_subtitle),
                    value = if (m.bomItemsCount > 0) "${m.completedBomItemCount}/${m.bomItemsCount}" else stringResource(R.string.overview_bom_placeholder),
                    goalHours = null,
                    progress = m.bomCompletionFraction?.toFloat(),
                    onClick = onOpenBom,
                )
            }
        }

        LoadsCard(state, m, onAddLoad, onOpenLibrary)
        BatteriesCard(state, m, onAddBattery)
        ChargersCard(state, m, onAddCharger)
    }

    goalEditor?.let { kind ->
        val currentGoal = if (kind == GoalKind.RUNTIME) system?.targetRuntimeHours else system?.targetChargeTimeHours
        val estimate = if (kind == GoalKind.RUNTIME) m.estimatedRuntimeHours else m.estimatedChargeHours
        GoalEditorDialog(
            title = stringResource(if (kind == GoalKind.RUNTIME) R.string.overview_runtime_goal_title else R.string.overview_chargetime_goal_title),
            initialHours = currentGoal ?: estimate ?: 8.0,
            hasGoal = currentGoal != null,
            onSave = { hours -> if (kind == GoalKind.RUNTIME) onSetRuntimeGoal(hours) else onSetChargeGoal(hours) },
            onRemove = { if (kind == GoalKind.RUNTIME) onSetRuntimeGoal(null) else onSetChargeGoal(null) },
            onDismiss = { goalEditor = null },
        )
    }
}

enum class GoalKind { RUNTIME, CHARGE }

private fun goalProgress(actual: Double?, goal: Double?, charge: Boolean): Float? {
    if (actual == null || goal == null || goal <= 0) return null
    return if (charge) (goal / maxOf(actual, 0.0001)).coerceIn(0.0, 1.0).toFloat()
    else (actual / goal).coerceIn(0.0, 1.0).toFloat()
}

@Composable
private fun MetricRow(
    icon: ImageVector,
    tint: Color,
    title: String,
    subtitle: String,
    value: String,
    goalHours: Double?,
    progress: Float?,
    onClick: () -> Unit,
) {
    Column(Modifier.fillMaxWidth().clickable { onClick() }) {
        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp))
            Column(Modifier.weight(1f)) {
                Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium)
                Text(subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            }
            Column(horizontalAlignment = Alignment.End) {
                Text(value, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                if (goalHours != null) {
                    Text(stringResource(R.string.overview_goal_label, formatDurationHours(goalHours)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
        }
        if (progress != null) {
            LinearProgressIndicator(progress = { progress }, color = tint, modifier = Modifier.fillMaxWidth().padding(top = 6.dp))
        }
    }
}

@Composable
private fun OverviewCard(title: String, content: @Composable () -> Unit) {
    Surface(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
        shape = RoundedCornerShape(20.dp),
        color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
    ) {
        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
            Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            content()
        }
    }
}

@Composable
private fun LoadsCard(state: DetailState, m: SystemMetrics, onAddLoad: () -> Unit, onOpenLibrary: () -> Unit) {
    OverviewCard(stringResource(R.string.loads_overview_header_title)) {
        if (state.loads.isEmpty()) {
            Text(stringResource(R.string.overview_loads_empty_title), fontWeight = FontWeight.Medium)
            Text(stringResource(R.string.overview_loads_empty_subtitle), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                Button(onClick = onAddLoad) { Text(stringResource(R.string.loads_empty_create)) }
            }
        } else {
            Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
                SummaryMetric(Icons.Outlined.ListAlt, state.loads.size.toString(), stringResource(R.string.loads_metric_count), MaterialTheme.colorScheme.primary)
                SummaryMetric(Icons.Outlined.Bolt, "${Fmt.number(m.totalCurrent)} A", stringResource(R.string.loads_metric_current), SysOrange)
                SummaryMetric(Icons.Outlined.Speed, "${Fmt.number(m.totalPower)} W", stringResource(R.string.loads_metric_power), SysGreen)
            }
        }
    }
}

@Composable
private fun BatteriesCard(state: DetailState, m: SystemMetrics, onAddBattery: () -> Unit) {
    OverviewCard(stringResource(R.string.battery_bank_header_title)) {
        if (state.batteries.isEmpty()) {
            Text(stringResource(R.string.battery_empty_title), fontWeight = FontWeight.Medium)
            Button(onClick = onAddBattery) { Text(stringResource(R.string.battery_empty_create)) }
        } else {
            Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
                SummaryMetric(Icons.Outlined.BatteryFull, state.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.Bolt, "${Fmt.number(m.totalUsableEnergy)} Wh", stringResource(R.string.battery_metric_usable_energy), SysGreen)
            }
        }
    }
}

@Composable
private fun ChargersCard(state: DetailState, m: SystemMetrics, onAddCharger: () -> Unit) {
    OverviewCard(stringResource(R.string.overview_chargers_header_title)) {
        if (state.chargers.isEmpty()) {
            Text(stringResource(R.string.overview_chargers_empty_title), fontWeight = FontWeight.Medium)
            Text(stringResource(R.string.overview_chargers_empty_subtitle), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            Button(onClick = onAddCharger) { Text(stringResource(R.string.overview_chargers_empty_create)) }
        } else {
            Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
                SummaryMetric(Icons.Outlined.Bolt, state.chargers.size.toString(), stringResource(R.string.chargers_metric_count), SysBlue)
                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), SysGreen)
            }
        }
    }
}
