package app.voltplan.cable.ui.system

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.BatteryFull
import androidx.compose.material.icons.outlined.Bolt
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.PictureAsPdf
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.platform.LocalContext
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 androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import app.voltplan.cable.CableApplication
import app.voltplan.cable.R
import app.voltplan.cable.ui.LocalUnitSettings
import app.voltplan.cable.ui.batteries.BatteriesTab
import app.voltplan.cable.ui.chargers.ChargersTab
import app.voltplan.cable.ui.components.AppearanceEditorSheet
import app.voltplan.cable.ui.loads.ComponentsTab
import app.voltplan.cable.ui.overview.OverviewTab
import app.voltplan.cable.ui.sfSymbol
import app.voltplan.cable.ui.systemIconOptions
import app.voltplan.cable.ui.theme.componentColor
import app.voltplan.cable.pdf.SystemOverviewPdf
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import kotlinx.coroutines.launch

enum class ComponentTab(val analytics: String) {
    OVERVIEW("overview"),
    COMPONENTS("components"),
    BATTERIES("batteries"),
    CHARGERS("chargers"),
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SystemDetailScreen(
    systemId: String,
    onBack: () -> Unit,
    onOpenLoad: (String) -> Unit,
    onNewLoad: () -> Unit,
    onEditBattery: (String) -> Unit,
    onNewBattery: () -> Unit,
    onEditCharger: (String) -> Unit,
    onNewCharger: () -> Unit,
    onOpenBom: () -> Unit,
    onOpenLibrary: () -> Unit,
) {
    val context = LocalContext.current
    val app = context.applicationContext as CableApplication
    val vm: SystemDetailViewModel = viewModel(
        key = "system-$systemId",
        factory = viewModelFactory { initializer { SystemDetailViewModel(app, systemId) } },
    )
    val state by vm.state.collectAsStateWithLifecycle()
    val settings = LocalUnitSettings.current
    val unitSystem by settings.unitSystem.collectAsStateWithLifecycle()
    val scope = rememberCoroutineScope()

    var tab by rememberSaveableTab()
    var showSystemEditor by remember { mutableStateOf(false) }
    var showOverviewMenu by remember { mutableStateOf(false) }
    val system = state.system

    Scaffold(
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = stringResource(R.string.action_back))
                    }
                },
                title = {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.clip(RoundedCornerShape(8.dp)),
                    ) {
                        if (system != null) {
                            Box(
                                Modifier.size(28.dp).clip(RoundedCornerShape(6.dp)).background(componentColor(system.colorName)),
                                contentAlignment = Alignment.Center,
                            ) {
                                Icon(sfSymbol(system.iconName), contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp))
                            }
                            Text(
                                system.name,
                                fontWeight = FontWeight.SemiBold,
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(start = 8.dp).clickable { showSystemEditor = true },
                            )
                        }
                    }
                },
                actions = {
                    when (tab) {
                        ComponentTab.OVERVIEW -> {
                            IconButton(onClick = { showOverviewMenu = true }) {
                                Icon(Icons.Outlined.PictureAsPdf, contentDescription = stringResource(R.string.overview_share_pdf))
                            }
                            DropdownMenu(expanded = showOverviewMenu, onDismissRequest = { showOverviewMenu = false }) {
                                DropdownMenuItem(
                                    text = { Text(stringResource(R.string.overview_share_pdf)) },
                                    onClick = {
                                        showOverviewMenu = false
                                        scope.launch {
                                            SystemOverviewPdf.exportAndShare(context, state, unitSystem)
                                        }
                                    },
                                )
                            }
                        }
                        ComponentTab.COMPONENTS -> IconButton(onClick = onNewLoad) {
                            Icon(Icons.Outlined.Add, contentDescription = stringResource(R.string.action_add))
                        }
                        ComponentTab.BATTERIES -> IconButton(onClick = onNewBattery) {
                            Icon(Icons.Outlined.Add, contentDescription = stringResource(R.string.action_add))
                        }
                        ComponentTab.CHARGERS -> IconButton(onClick = onNewCharger) {
                            Icon(Icons.Outlined.Add, contentDescription = stringResource(R.string.action_add))
                        }
                    }
                },
            )
        },
        bottomBar = {
            NavigationBar {
                NavTab(tab, ComponentTab.OVERVIEW, Icons.Outlined.Dashboard, stringResource(R.string.tab_overview)) { tab = it; vm.logTabChange(it.analytics) }
                NavTab(tab, ComponentTab.COMPONENTS, Icons.Outlined.Layers, stringResource(R.string.tab_components)) { tab = it; vm.logTabChange(it.analytics) }
                NavTab(tab, ComponentTab.BATTERIES, Icons.Outlined.BatteryFull, stringResource(R.string.tab_batteries)) { tab = it; vm.logTabChange(it.analytics) }
                NavTab(tab, ComponentTab.CHARGERS, Icons.Outlined.Bolt, stringResource(R.string.tab_chargers)) { tab = it; vm.logTabChange(it.analytics) }
            }
        },
    ) { padding ->
        Box(Modifier.padding(padding)) {
            when (tab) {
                ComponentTab.OVERVIEW -> OverviewTab(
                    state = state,
                    unitSystem = unitSystem,
                    onAddLoad = onNewLoad,
                    onAddBattery = onNewBattery,
                    onAddCharger = onNewCharger,
                    onOpenLibrary = onOpenLibrary,
                    onOpenBom = { vm.logBomOpened(); onOpenBom() },
                    onSetRuntimeGoal = vm::setRuntimeGoal,
                    onSetChargeGoal = vm::setChargeGoal,
                )
                ComponentTab.COMPONENTS -> ComponentsTab(
                    state = state,
                    unitSystem = unitSystem,
                    onOpenLoad = onOpenLoad,
                    onNewLoad = onNewLoad,
                    onOpenLibrary = onOpenLibrary,
                    onDeleteLoad = vm::deleteLoad,
                )
                ComponentTab.BATTERIES -> BatteriesTab(
                    state = state,
                    onEditBattery = onEditBattery,
                    onNewBattery = onNewBattery,
                    onDeleteBattery = vm::deleteBattery,
                )
                ComponentTab.CHARGERS -> ChargersTab(
                    state = state,
                    onEditCharger = onEditCharger,
                    onNewCharger = onNewCharger,
                    onDeleteCharger = vm::deleteCharger,
                )
            }
        }
    }

    if (showSystemEditor && system != null) {
        var location by remember { mutableStateOf(system.location) }
        AppearanceEditorSheet(
            title = stringResource(R.string.editor_system_title),
            nameLabel = stringResource(R.string.editor_system_name),
            previewSubtitle = location.ifBlank { stringResource(R.string.editor_system_location) },
            icons = systemIconOptions,
            initialName = system.name,
            initialIcon = system.iconName,
            initialColor = system.colorName,
            extra = {
                OutlinedTextField(
                    value = location,
                    onValueChange = { location = it },
                    label = { Text(stringResource(R.string.editor_system_location)) },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                )
            },
            onSave = { name, icon, color -> vm.saveSystem(name, location, icon, color) },
            onDismiss = { showSystemEditor = false },
        )
    }
}

@Composable
private fun RowScope.NavTab(
    current: ComponentTab,
    tab: ComponentTab,
    icon: ImageVector,
    label: String,
    onSelect: (ComponentTab) -> Unit,
) {
    NavigationBarItem(
        selected = current == tab,
        onClick = { if (current != tab) onSelect(tab) },
        icon = { Icon(icon, contentDescription = label) },
        label = { Text(label) },
    )
}

@Composable
private fun rememberSaveableTab() = remember { mutableStateOf(ComponentTab.OVERVIEW) }
