package eu.darken.bluemusic.main.ui.settings.general

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.twotone.Palette
import androidx.compose.material.icons.twotone.Translate
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.darken.bluemusic.R
import eu.darken.bluemusic.common.compose.Preview2
import eu.darken.bluemusic.common.compose.PreviewWrapper
import eu.darken.bluemusic.common.compose.UpgradeBadge
import eu.darken.bluemusic.common.compose.horizontalCutoutPadding
import eu.darken.bluemusic.common.compose.navigationBarBottomPadding
import eu.darken.bluemusic.common.error.ErrorEventHandler
import eu.darken.bluemusic.common.settings.EnumSelectorDialog
import eu.darken.bluemusic.common.settings.SettingsCategoryHeader
import eu.darken.bluemusic.common.settings.SettingsDivider
import eu.darken.bluemusic.common.settings.SettingsPreferenceItem
import eu.darken.bluemusic.common.theming.ThemeColor
import eu.darken.bluemusic.common.theming.ThemeMode
import eu.darken.bluemusic.common.theming.ThemeStyle
import androidx.lifecycle.compose.collectAsStateWithLifecycle

@Composable
fun GeneralSettingsScreenHost(vm: GeneralSettingsViewModel = hiltViewModel()) {
    ErrorEventHandler(vm)

    val state by vm.state.collectAsStateWithLifecycle()
    var activeDialog by remember { mutableStateOf<GeneralSettingsDialog?>(null) }

    LaunchedEffect(Unit) {
        vm.events.collect { dialog -> activeDialog = dialog }
    }

    state?.let { vmState ->
        GeneralSettingsScreen(
            state = vmState,
            activeDialog = activeDialog,
            onNavigateUp = { vm.navUp() },
            onLanguageSwitcher = { vm.showLanguagePicker() },
            onThemeRowClicked = { vm.onThemeRowClicked(it) },
            onThemeModeSelected = { vm.updateThemeMode(it) },
            onThemeStyleSelected = { vm.updateThemeStyle(it) },
            onThemeColorSelected = { vm.updateThemeColor(it) },
            onDialogDismissed = { activeDialog = null },
        )
    }
}

@Composable
fun GeneralSettingsScreen(
    state: GeneralSettingsViewModel.State,
    activeDialog: GeneralSettingsDialog? = null,
    onNavigateUp: () -> Unit,
    onLanguageSwitcher: (() -> Unit)?,
    onThemeRowClicked: (GeneralSettingsDialog) -> Unit,
    onThemeModeSelected: (ThemeMode) -> Unit,
    onThemeStyleSelected: (ThemeStyle) -> Unit,
    onThemeColorSelected: (ThemeColor) -> Unit,
    onDialogDismissed: () -> Unit,
) {
    val context = LocalContext.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.general_settings_label)) },
                navigationIcon = {
                    IconButton(onClick = onNavigateUp) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription =
                                stringResource(R.string.general_back_action)
                        )
                    }
                }
            )
        },
        contentWindowInsets = WindowInsets.statusBars
    ) { paddingValues ->
        val navBarPadding = navigationBarBottomPadding()
        val isMaterialYou = state.themeState.style == ThemeStyle.MATERIAL_YOU
        val proTitleBadge: @Composable (String) -> Unit = { title ->
            Row {
                Text(
                    text = title,
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Spacer(modifier = Modifier.width(6.dp))
                UpgradeBadge()
            }
        }
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .horizontalCutoutPadding(),
            contentPadding = PaddingValues(bottom = navBarPadding),
            verticalArrangement = Arrangement.Top
        ) {
            item {
                SettingsCategoryHeader(text = stringResource(R.string.settings_category_ui_label))
            }

            item {
                SettingsPreferenceItem(
                    icon = Icons.TwoTone.Palette,
                    title = stringResource(R.string.ui_theme_mode_setting_label),
                    titleContent = if (!state.isUpgraded) {
                        { proTitleBadge(stringResource(R.string.ui_theme_mode_setting_label)) }
                    } else {
                        null
                    },
                    subtitle = stringResource(R.string.ui_theme_mode_setting_explanation),
                    value = if (state.isUpgraded) state.themeState.mode.label.get(context) else null,
                    onClick = { onThemeRowClicked(GeneralSettingsDialog.THEME_MODE) },
                )
                SettingsDivider()
            }

            item {
                SettingsPreferenceItem(
                    icon = Icons.TwoTone.Palette,
                    title = stringResource(R.string.ui_theme_style_setting_label),
                    titleContent = if (!state.isUpgraded) {
                        { proTitleBadge(stringResource(R.string.ui_theme_style_setting_label)) }
                    } else {
                        null
                    },
                    subtitle = stringResource(R.string.ui_theme_style_setting_explanation),
                    value = if (state.isUpgraded) state.themeState.style.label.get(context) else null,
                    onClick = { onThemeRowClicked(GeneralSettingsDialog.THEME_STYLE) },
                )
                SettingsDivider()
            }

            item {
                SettingsPreferenceItem(
                    icon = Icons.TwoTone.Palette,
                    title = stringResource(R.string.ui_theme_color_setting_label),
                    titleContent = if (!state.isUpgraded) {
                        { proTitleBadge(stringResource(R.string.ui_theme_color_setting_label)) }
                    } else {
                        null
                    },
                    subtitle = if (isMaterialYou) {
                        stringResource(R.string.ui_theme_color_material_you_note)
                    } else {
                        stringResource(R.string.ui_theme_color_setting_explanation)
                    },
                    value = if (state.isUpgraded && !isMaterialYou) state.themeState.color.label.get(context) else null,
                    onClick = { onThemeRowClicked(GeneralSettingsDialog.THEME_COLOR) },
                )
                SettingsDivider()
            }

            onLanguageSwitcher?.let { action ->
                item {
                    SettingsPreferenceItem(
                        icon = Icons.TwoTone.Translate,
                        title = stringResource(R.string.ui_language_override_label),
                        subtitle = stringResource(R.string.ui_language_override_desc),
                        onClick = { action.invoke() }
                    )
                    SettingsDivider()
                }
            }
        }
    }

    when (activeDialog) {
        GeneralSettingsDialog.THEME_MODE -> EnumSelectorDialog(
            title = stringResource(R.string.ui_theme_mode_setting_label),
            options = ThemeMode.entries,
            selectedOption = state.themeState.mode,
            onOptionSelected = { mode ->
                onThemeModeSelected(mode)
                onDialogDismissed()
            },
            onDismiss = onDialogDismissed,
        )

        GeneralSettingsDialog.THEME_STYLE -> EnumSelectorDialog(
            title = stringResource(R.string.ui_theme_style_setting_label),
            options = ThemeStyle.entries,
            selectedOption = state.themeState.style,
            onOptionSelected = { style ->
                onThemeStyleSelected(style)
                onDialogDismissed()
            },
            onDismiss = onDialogDismissed,
        )

        GeneralSettingsDialog.THEME_COLOR -> EnumSelectorDialog(
            title = stringResource(R.string.ui_theme_color_setting_label),
            options = ThemeColor.entries,
            selectedOption = state.themeState.color,
            onOptionSelected = { color ->
                onThemeColorSelected(color)
                onDialogDismissed()
            },
            onDismiss = onDialogDismissed,
        )

        null -> Unit
    }
}

@Preview2
@Composable
private fun GeneralSettingsScreenPreview() {
    PreviewWrapper {
        GeneralSettingsScreen(
            state = GeneralSettingsViewModel.State(isUpgraded = true),
            onNavigateUp = {},
            onLanguageSwitcher = {},
            onThemeRowClicked = {},
            onThemeModeSelected = {},
            onThemeStyleSelected = {},
            onThemeColorSelected = {},
            onDialogDismissed = {},
        )
    }
}
