package com.applemand.zmanim.feature.settings

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
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.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.foundation.layout.Row
import androidx.compose.ui.Alignment
import com.applemand.zmanim.core.settings.proto.Language
import com.applemand.zmanim.core.settings.proto.ThemeMode
import com.applemand.zmanim.core.zmanim.ZmanKey

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onBack: () -> Unit,
    onPickLocation: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: SettingsViewModel = hiltViewModel(),
) {
    val settings by viewModel.state.collectAsStateWithLifecycle()

    Scaffold(
        modifier = modifier,
        topBar = {
            TopAppBar(
                title = { Text("Settings") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
            )
        },
    ) { padding ->
        val s = settings ?: return@Scaffold
        var showLanguageDialog by remember { mutableStateOf(false) }
        var showThemeDialog by remember { mutableStateOf(false) }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(0.dp),
        ) {
            SectionTitle("General")
            ListItem(
                headlineContent = { Text("Location") },
                supportingContent = { Text(s.currentLocation.nameEn) },
                modifier = Modifier.padding(horizontal = 4.dp),
                trailingContent = { IconButton(onClick = onPickLocation) {
                    Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
                } },
            )
            ListItem(
                headlineContent = { Text("Language") },
                supportingContent = { Text(when (s.uiLanguage) {
                    Language.LANGUAGE_ENGLISH -> "English"
                    Language.LANGUAGE_HEBREW -> "עברית"
                    else -> "System"
                }) },
                modifier = Modifier.clickable { showLanguageDialog = true },
                trailingContent = {
                    Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
                },
            )
            ListItem(
                headlineContent = { Text("Theme") },
                supportingContent = { Text(when (s.themeMode) {
                    ThemeMode.THEME_LIGHT -> "Light"
                    ThemeMode.THEME_DARK -> "Dark"
                    else -> "System"
                }) },
                modifier = Modifier.clickable { showThemeDialog = true },
                trailingContent = {
                    Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
                },
            )
            ListItem(
                headlineContent = { Text("Dynamic color (Android 12+)") },
                trailingContent = {
                    Switch(checked = s.useDynamicColor, onCheckedChange = viewModel::setUseDynamicColor)
                },
            )
            ListItem(
                headlineContent = { Text("12-hour clock") },
                trailingContent = {
                    Switch(checked = s.twelveHourClock, onCheckedChange = viewModel::setTwelveHourClock)
                },
            )
            ListItem(
                headlineContent = { Text("Israeli holiday schedule") },
                supportingContent = { Text("Single-day yom tov / Parshiyot for Eretz Yisroel") },
                trailingContent = {
                    Switch(checked = s.inIsrael, onCheckedChange = viewModel::setInIsrael)
                },
            )

            HorizontalDivider()
            SectionTitle("Display")
            ListItem(
                headlineContent = { Text("Show Daf Yomi") },
                trailingContent = {
                    Switch(checked = s.showDafYomi, onCheckedChange = viewModel::setShowDafYomi)
                },
            )

            HorizontalDivider()
            SectionTitle("Zmanim")
            ListItem(
                headlineContent = { Text("Show zmanim") },
                trailingContent = {
                    Switch(checked = s.showZmanim, onCheckedChange = viewModel::setShowZmanim)
                },
            )
            if (s.showZmanim) {
                ListItem(
                    headlineContent = { Text("Show seconds") },
                    trailingContent = {
                        Switch(checked = s.showZmanimSeconds,
                            onCheckedChange = viewModel::setShowZmanimSeconds)
                    },
                )
                ZmanKey.entries.forEach { zk ->
                    val visible = s.zmanimVisibleMap[zk.keyId] ?: true
                    ListItem(
                        headlineContent = { Text(zk.nameEn) },
                        supportingContent = { Text(zk.nameHe, style = MaterialTheme.typography.labelSmall) },
                        trailingContent = {
                            Switch(
                                checked = visible,
                                onCheckedChange = { viewModel.setZmanVisible(zk.keyId, it) },
                            )
                        },
                    )
                }
            }
            ListItem(
                headlineContent = { Text("Candle lighting: ${s.candleLightingMinutes} min before sunset") },
                supportingContent = {
                    Slider(
                        value = s.candleLightingMinutes.toFloat(),
                        onValueChange = { viewModel.setCandleLightingMinutes(it.toInt()) },
                        valueRange = 1f..60f,
                        steps = 59,
                    )
                },
            )
            ListItem(
                headlineContent = { Text("Use elevation for sunrise/sunset") },
                supportingContent = { Text(
                    "Elevation-aware times (visible horizon). Off = sea-level minhag — " +
                        "the diaspora default. Affects sunrise, sunset, candle lighting, and all derived zmanim."
                ) },
                trailingContent = {
                    Switch(checked = s.useElevationForZmanim,
                        onCheckedChange = viewModel::setUseElevation)
                },
            )
            ListItem(
                headlineContent = { Text("Havdalah: ${s.havdalahMinutes} min after sunset") },
                supportingContent = {
                    Slider(
                        value = s.havdalahMinutes.toFloat(),
                        onValueChange = { viewModel.setHavdalahMinutes(it.toInt()) },
                        valueRange = 30f..90f,
                        steps = 60,
                    )
                },
            )

            HorizontalDivider()
            SectionTitle("Holiday filters")
            HolidaySwitch("Yom Tov", s.holidayFilters.yomTov) {
                viewModel.setHolidayFilters(it, s.holidayFilters.fast, s.holidayFilters.minor, s.holidayFilters.roshChodesh)
            }
            HolidaySwitch("Fast days", s.holidayFilters.fast) {
                viewModel.setHolidayFilters(s.holidayFilters.yomTov, it, s.holidayFilters.minor, s.holidayFilters.roshChodesh)
            }
            HolidaySwitch("Minor holidays", s.holidayFilters.minor) {
                viewModel.setHolidayFilters(s.holidayFilters.yomTov, s.holidayFilters.fast, it, s.holidayFilters.roshChodesh)
            }
            HolidaySwitch("Rosh Chodesh", s.holidayFilters.roshChodesh) {
                viewModel.setHolidayFilters(s.holidayFilters.yomTov, s.holidayFilters.fast, s.holidayFilters.minor, it)
            }

            HorizontalDivider()
            SectionTitle("Notifications")
            ListItem(
                headlineContent = { Text("Enable notifications") },
                supportingContent = { Text("Daily morning summary, candle lighting, fasts") },
                trailingContent = {
                    Switch(checked = s.enableNotifications,
                        onCheckedChange = viewModel::setEnableNotifications)
                },
            )

            HorizontalDivider()
            SectionTitle("Location")
            ListItem(
                headlineContent = { Text("Auto-sync location") },
                supportingContent = { Text("Uses GPS only — no network") },
                trailingContent = {
                    Switch(checked = s.autoSyncLocation,
                        onCheckedChange = viewModel::setAutoSyncLocation)
                },
            )

            HorizontalDivider()
            SectionTitle("Calendar export")
            ListItem(
                headlineContent = { Text("Sync duration: ${s.syncZmanimDays} days") },
                supportingContent = {
                    Slider(
                        value = s.syncZmanimDays.toFloat(),
                        onValueChange = { viewModel.setSyncDays(it.toInt()) },
                        valueRange = 7f..365f,
                        steps = 0,
                    )
                },
            )
        }

        if (showLanguageDialog) {
            RadioPickerDialog(
                title = "Language",
                options = listOf(
                    Language.LANGUAGE_SYSTEM to "System default",
                    Language.LANGUAGE_ENGLISH to "English",
                    Language.LANGUAGE_HEBREW to "עברית",
                ),
                selected = s.uiLanguage,
                onSelect = {
                    viewModel.setLanguage(it)
                    showLanguageDialog = false
                },
                onDismiss = { showLanguageDialog = false },
            )
        }
        if (showThemeDialog) {
            RadioPickerDialog(
                title = "Theme",
                options = listOf(
                    ThemeMode.THEME_SYSTEM to "System default",
                    ThemeMode.THEME_LIGHT to "Light",
                    ThemeMode.THEME_DARK to "Dark",
                ),
                selected = s.themeMode,
                onSelect = {
                    viewModel.setThemeMode(it)
                    showThemeDialog = false
                },
                onDismiss = { showThemeDialog = false },
            )
        }
    }
}

@Composable
private fun <T> RadioPickerDialog(
    title: String,
    options: List<Pair<T, String>>,
    selected: T,
    onSelect: (T) -> Unit,
    onDismiss: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column {
                options.forEach { (value, label) ->
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .clickable { onSelect(value) }
                            .padding(vertical = 8.dp),
                    ) {
                        RadioButton(selected = value == selected, onClick = { onSelect(value) })
                        Text(label, modifier = Modifier.padding(start = 8.dp))
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) { Text("Cancel") }
        },
    )
}

@Composable
private fun SectionTitle(text: String) {
    Text(
        text = text,
        style = MaterialTheme.typography.labelLarge,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
    )
}

@Composable
private fun HolidaySwitch(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
    ListItem(
        headlineContent = { Text(label) },
        trailingContent = { Switch(checked = value, onCheckedChange = onChange) },
    )
}
