package de.softwareapp_hb.privateqrscanner.ui.screens

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
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.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import de.softwareapp_hb.privateqrscanner.R
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleCatalog
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleOption
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleStatus
import de.softwareapp_hb.privateqrscanner.ui.UseCaseView
import de.softwareapp_hb.privateqrscanner.ui.theme.PrivateQrColors
import de.softwareapp_hb.privateqrscanner.util.InAppReviewRequester

@Composable
fun SettingsScreen(
    historyEnabled: Boolean,
    warningsEnabled: Boolean,
    scanFeedbackEnabled: Boolean,
    selectedUseCaseView: UseCaseView,
    appLocaleOptions: List<AppLocaleOption>,
    selectedAppLanguageTag: String,
    onHistoryToggle: (Boolean, Boolean) -> Unit,
    onWarningsToggle: (Boolean) -> Unit,
    onScanFeedbackToggle: (Boolean) -> Unit,
    onUseCaseViewSelected: (UseCaseView) -> Unit,
    onAppLanguageSelected: (String) -> Unit
) {
    val context = LocalContext.current
    val showDeleteConfirm = remember { mutableStateOf(false) }
    val showPrivacyPolicy = remember { mutableStateOf(false) }

    if (showDeleteConfirm.value) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirm.value = false },
            title = { Text(stringResource(R.string.settings)) },
            text = { Text(stringResource(R.string.delete_history_on_disable)) },
            confirmButton = {
                TextButton(onClick = {
                    onHistoryToggle(false, true)
                    showDeleteConfirm.value = false
                }) { Text(stringResource(R.string.confirm)) }
            },
            dismissButton = {
                TextButton(onClick = {
                    onHistoryToggle(false, false)
                    showDeleteConfirm.value = false
                }) { Text(stringResource(R.string.cancel)) }
            }
        )
    }

    if (showPrivacyPolicy.value) {
        PrivacyPolicyDialog(onDismiss = { showPrivacyPolicy.value = false })
    }

    BoxWithConstraints(
        modifier = Modifier
            .fillMaxSize()
            .background(PrivateQrColors.AppBackground)
    ) {
        val wideLayout = maxWidth >= 600.dp

        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            SettingsHeader()

            if (wideLayout) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(24.dp),
                    verticalAlignment = Alignment.Top
                ) {
                    Column(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(18.dp)
                    ) {
                        SettingsToggleCard(
                            historyEnabled = historyEnabled,
                            warningsEnabled = warningsEnabled,
                            scanFeedbackEnabled = scanFeedbackEnabled,
                            onHistoryToggle = onHistoryToggle,
                            onWarningsToggle = onWarningsToggle,
                            onScanFeedbackToggle = onScanFeedbackToggle,
                            onRequestDisableHistory = { showDeleteConfirm.value = true }
                        )
                        LanguageSelectionCard(
                            appLocaleOptions = appLocaleOptions,
                            selectedAppLanguageTag = selectedAppLanguageTag,
                            onAppLanguageSelected = onAppLanguageSelected
                        )
                        AboutCard(
                            onPrivacyClick = { showPrivacyPolicy.value = true },
                            onReviewClick = { InAppReviewRequester.requestReview(context) }
                        )
                    }
                    UseCaseSelectionCard(
                        selectedUseCaseView = selectedUseCaseView,
                        onUseCaseViewSelected = onUseCaseViewSelected,
                        modifier = Modifier.weight(0.9f)
                    )
                }
            } else {
                SettingsToggleCard(
                    historyEnabled = historyEnabled,
                    warningsEnabled = warningsEnabled,
                    scanFeedbackEnabled = scanFeedbackEnabled,
                    onHistoryToggle = onHistoryToggle,
                    onWarningsToggle = onWarningsToggle,
                    onScanFeedbackToggle = onScanFeedbackToggle,
                    onRequestDisableHistory = { showDeleteConfirm.value = true }
                )
                LanguageSelectionCard(
                    appLocaleOptions = appLocaleOptions,
                    selectedAppLanguageTag = selectedAppLanguageTag,
                    onAppLanguageSelected = onAppLanguageSelected
                )
                UseCaseSelectionCard(
                    selectedUseCaseView = selectedUseCaseView,
                    onUseCaseViewSelected = onUseCaseViewSelected
                )
                AboutCard(
                    onPrivacyClick = { showPrivacyPolicy.value = true },
                    onReviewClick = { InAppReviewRequester.requestReview(context) }
                )
            }

            Spacer(modifier = Modifier.height(12.dp))
        }
    }
}

@Composable
private fun LanguageSelectionCard(
    appLocaleOptions: List<AppLocaleOption>,
    selectedAppLanguageTag: String,
    onAppLanguageSelected: (String) -> Unit
) {
    val showPicker = remember { mutableStateOf(false) }
    val selectedOption = AppLocaleCatalog.resolveOption(appLocaleOptions, selectedAppLanguageTag)

    if (showPicker.value) {
        LanguagePickerDialog(
            appLocaleOptions = appLocaleOptions,
            selectedAppLanguageTag = selectedOption.storageTag,
            onSelect = { option ->
                onAppLanguageSelected(option.storageTag)
                showPicker.value = false
            },
            onDismiss = { showPicker.value = false }
        )
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { showPicker.value = true },
        colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
        shape = RoundedCornerShape(28.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(
                    text = stringResource(R.string.app_language),
                    color = PrivateQrColors.TextPrimary,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.ExtraBold
                )
                Text(
                    text = selectedOption.displayLabel(),
                    color = PrivateQrColors.TextSecondary,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.SemiBold
                )
            }
            TextButton(
                onClick = { showPicker.value = true },
                colors = ButtonDefaults.textButtonColors(contentColor = PrivateQrColors.Teal700)
            ) {
                Text(text = stringResource(R.string.change), fontWeight = FontWeight.Bold)
            }
        }
    }
}

@Composable
private fun LanguagePickerDialog(
    appLocaleOptions: List<AppLocaleOption>,
    selectedAppLanguageTag: String,
    onSelect: (AppLocaleOption) -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.app_language)) },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 420.dp)
                    .verticalScroll(rememberScrollState())
            ) {
                appLocaleOptions.forEach { option ->
                    LanguagePickerRow(
                        option = option,
                        selected = option.storageTag == selectedAppLanguageTag,
                        onClick = { onSelect(option) }
                    )
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text(stringResource(R.string.close))
            }
        }
    )
}

@Composable
private fun LanguagePickerRow(
    option: AppLocaleOption,
    selected: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 56.dp)
            .clickable(onClick = onClick)
            .padding(vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        RadioButton(
            selected = selected,
            onClick = onClick,
            colors = RadioButtonDefaults.colors(selectedColor = PrivateQrColors.Teal700)
        )
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = option.displayLabel(),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Bold
            )
            if (option.status == AppLocaleStatus.Partial) {
                Text(
                    text = stringResource(R.string.app_language_partial_translation),
                    color = PrivateQrColors.TextSecondary,
                    style = MaterialTheme.typography.bodySmall,
                    fontWeight = FontWeight.SemiBold
                )
            }
        }
    }
}

@Composable
private fun AppLocaleOption.displayLabel(): String {
    return if (isSystemDefault) {
        stringResource(R.string.app_language_system_default)
    } else {
        displayName
    }
}

@Composable
private fun SettingsToggleCard(
    historyEnabled: Boolean,
    warningsEnabled: Boolean,
    scanFeedbackEnabled: Boolean,
    onHistoryToggle: (Boolean, Boolean) -> Unit,
    onWarningsToggle: (Boolean) -> Unit,
    onScanFeedbackToggle: (Boolean) -> Unit,
    onRequestDisableHistory: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
        shape = RoundedCornerShape(28.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)) {
            SettingsToggleRow(
                title = stringResource(R.string.save_history),
                checked = historyEnabled,
                onCheckedChange = { enabled ->
                    if (!enabled && historyEnabled) {
                        onRequestDisableHistory()
                    } else {
                        onHistoryToggle(enabled, false)
                    }
                }
            )
            SettingsDivider()
            SettingsToggleRow(
                title = stringResource(R.string.security_warnings),
                checked = warningsEnabled,
                onCheckedChange = onWarningsToggle
            )
            SettingsDivider()
            SettingsToggleRow(
                title = stringResource(R.string.scan_feedback),
                checked = scanFeedbackEnabled,
                onCheckedChange = onScanFeedbackToggle
            )
        }
    }
}

@Composable
private fun UseCaseSelectionCard(
    selectedUseCaseView: UseCaseView,
    onUseCaseViewSelected: (UseCaseView) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Text(
            text = stringResource(R.string.select_use_case_view),
            color = PrivateQrColors.TextPrimary,
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.ExtraBold
        )
        UseCaseView.entries.forEach { candidate ->
            UseCasePickerOption(
                candidate = candidate,
                selected = candidate == selectedUseCaseView,
                onClick = { onUseCaseViewSelected(candidate) }
            )
        }
    }
}

@Composable
private fun AboutCard(
    onPrivacyClick: () -> Unit,
    onReviewClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = PrivateQrColors.Surface),
        shape = RoundedCornerShape(28.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            Text(
                text = stringResource(R.string.about),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.ExtraBold
            )
            InfoLine(stringResource(R.string.version))
            InfoLine(stringResource(R.string.licenses))
            InfoLine(stringResource(R.string.contact))
            Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                TextButton(
                    onClick = onPrivacyClick,
                    colors = ButtonDefaults.textButtonColors(contentColor = PrivateQrColors.Teal700)
                ) {
                    Text(text = stringResource(R.string.privacy_policy), fontWeight = FontWeight.Bold)
                }
                TextButton(
                    onClick = onReviewClick,
                    colors = ButtonDefaults.textButtonColors(contentColor = PrivateQrColors.Teal700)
                ) {
                    Text(text = stringResource(R.string.review_app), fontWeight = FontWeight.Bold)
                }
            }
        }
    }
}

@Composable
private fun UseCasePickerOption(
    candidate: UseCaseView,
    selected: Boolean,
    onClick: () -> Unit
) {
    val borderColor = if (selected) PrivateQrColors.Teal300 else Color.Transparent
    val backgroundColor = if (selected) Color(0xFFECFDF5) else PrivateQrColors.AppBackground
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(backgroundColor, RoundedCornerShape(24.dp))
            .border(2.dp, borderColor, RoundedCornerShape(24.dp))
            .clickable(onClick = onClick)
            .padding(18.dp),
        horizontalArrangement = Arrangement.spacedBy(16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            modifier = Modifier
                .size(58.dp)
                .background(PrivateQrColors.Mint, RoundedCornerShape(16.dp)),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = if (selected) "✓" else "◎",
                color = PrivateQrColors.Teal700,
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.ExtraBold
            )
        }
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = stringResource(candidate.titleRes),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(candidate.descriptionRes()),
                color = PrivateQrColors.TextSecondary,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.SemiBold
            )
        }
    }
}

private fun UseCaseView.descriptionRes(): Int {
    return when (this) {
        UseCaseView.EverydayPersonal -> R.string.use_case_everyday_description
        UseCaseView.EventTicketing -> R.string.use_case_event_ticketing_description
    }
}

@Composable
private fun SettingsHeader() {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(14.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_legacy),
            contentDescription = null,
            modifier = Modifier.size(64.dp)
        )
        Column {
            Text(
                text = stringResource(R.string.app_name),
                color = PrivateQrColors.TextPrimary,
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(R.string.settings_header_subtitle),
                color = PrivateQrColors.TextSecondary,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Bold
            )
        }
    }
    Spacer(modifier = Modifier.height(18.dp))
    Card(
        colors = CardDefaults.cardColors(containerColor = Color.Transparent),
        shape = RoundedCornerShape(30.dp)
    ) {
        Column(
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        colors = listOf(PrivateQrColors.Navy, PrivateQrColors.Teal900)
                    )
                )
                .padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = stringResource(R.string.settings_hero_title),
                color = PrivateQrColors.Surface,
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.ExtraBold
            )
            Text(
                text = stringResource(R.string.settings_hero_subtitle),
                color = PrivateQrColors.Mint,
                style = MaterialTheme.typography.titleMedium
            )
        }
    }
}

@Composable
private fun SettingsToggleRow(
    title: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(74.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            color = PrivateQrColors.TextPrimary,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.ExtraBold
        )
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = PrivateQrColors.Surface,
                checkedTrackColor = PrivateQrColors.Teal700,
                uncheckedThumbColor = PrivateQrColors.Surface,
                uncheckedTrackColor = PrivateQrColors.TextSecondary.copy(alpha = 0.35f)
            )
        )
    }
}

@Composable
private fun SettingsDivider() {
    HorizontalDivider(color = PrivateQrColors.Divider)
}

@Composable
private fun InfoLine(text: String) {
    Text(
        text = text,
        color = PrivateQrColors.TextSecondary,
        style = MaterialTheme.typography.bodyMedium
    )
}
