@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.view.settings

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Build
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.BorderStroke
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.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
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.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.AllFonts
import eu.gaudian.translator.ui.theme.AllThemes
import eu.gaudian.translator.ui.theme.FontStyle
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTabLayout
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.TabItem
import eu.gaudian.translator.viewmodel.SettingsViewModel

private data class DarkModeOption(
    override val title: String,
    override val icon: ImageVector,
    val name: String
) : TabItem

@Suppress("HardCodedStringLiteral")
private fun getDarkModeOptions(context: Context): List<DarkModeOption> {
    return listOf(
        DarkModeOption(context.getString(R.string.text_light), AppIcons.LightMode, "Light"),
        DarkModeOption(context.getString(R.string.text_dark), AppIcons.DarkMode, "Dark"),
        DarkModeOption(context.getString(R.string.label_system), AppIcons.BrightnessAuto, "System")
    )
}

@Composable
fun LayoutOptionsScreen(navController: NavController) {
    val activity = LocalContext.current.findActivity()
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val context = LocalContext.current
    val selectedThemeName by settingsViewModel.theme.collectAsStateWithLifecycle()
    val selectedDarkMode by settingsViewModel.darkModePreference.collectAsStateWithLifecycle()
    val selectedFontName by settingsViewModel.fontPreference.collectAsStateWithLifecycle()
    val showBottomNavLabels by settingsViewModel.showBottomNavLabels.collectAsStateWithLifecycle()

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.label_appearance),
                onNavigateBack = { navController.popBackStack() },
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .padding(paddingValues)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(4.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            AppCard(Modifier.padding(0.dp)) {
                Column(Modifier.padding(0.dp)) {
                    Text(
                        text = stringResource(R.string.text_appearance_mode),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    val darkModeOptions = getDarkModeOptions(context)
                    val selectedMode = darkModeOptions.find { it.name == selectedDarkMode } ?: darkModeOptions.last()
                    AppTabLayout(
                        tabs = darkModeOptions,
                        selectedTab = selectedMode,
                        onTabSelected = { settingsViewModel.setDarkModePreference(it.name) }
                    )
                }
            }

            AppCard {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { settingsViewModel.setShowBottomNavLabels(!showBottomNavLabels) }
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = stringResource(R.string.text_navigation_bar_labels),
                            style = MaterialTheme.typography.titleMedium
                        )
                        Text(
                            text = stringResource(R.string.text_show_text_labels_on_the_main_navigation_bar),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    Spacer(Modifier.width(16.dp))
                    Switch(
                        checked = showBottomNavLabels,
                        onCheckedChange = { settingsViewModel.setShowBottomNavLabels(it) }
                    )
                }
            }

            // --- Color Palette Section ---
            AppCard {
                Column(Modifier.padding(16.dp)) {
                    Text(
                        text = stringResource(R.string.text_color_palette),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                    ThemePicker(
                        selectedThemeName = selectedThemeName,
                        onThemeSelected = { themeName ->
                            settingsViewModel.setTheme(themeName)
                            (context as? Activity)?.recreate()
                        }
                    )
                }
            }

            AppCard {
                Column(Modifier.padding(16.dp)) {
                    Text(
                        text = stringResource(R.string.text_font_style),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                    FontPicker(
                        selectedFontName = selectedFontName,
                        onFontSelected = { font ->
                            settingsViewModel.setFontPreference(font.name)
                            (context as? Activity)?.recreate()
                        }
                    )
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Composable
private fun ThemePicker(selectedThemeName: String, onThemeSelected: (String) -> Unit) {
    val isDynamicThemeSupported = remember { Build.VERSION.SDK_INT >= Build.VERSION_CODES.S }

    LazyRow(
        horizontalArrangement = Arrangement.spacedBy(16.dp),
        contentPadding = PaddingValues(horizontal = 4.dp)
    ) {
        // Add the System Dynamic Theme option if supported
        if (isDynamicThemeSupported) {
            item {
                SystemThemeOption(
                    isSelected = selectedThemeName == "System",
                    onClick = { onThemeSelected("System") }
                )
            }
        }
        items(AllThemes) { theme ->
            val isSelected = theme.name == selectedThemeName
            val borderColor by animateColorAsState(
                targetValue = if (isSelected) MaterialTheme.colorScheme.primary else Color.Transparent,
                animationSpec = spring(stiffness = Spring.StiffnessMedium),
                label = "borderColor"
            )

            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier
                    .clip(RoundedCornerShape(12.dp))
                    .clickable { onThemeSelected(theme.name) }
                    .padding(vertical = 4.dp)
            ) {
                Box(
                    modifier = Modifier
                        .size(64.dp)
                        .clip(CircleShape)
                        .border(
                            width = 3.dp,
                            color = borderColor,
                            shape = CircleShape
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Column(Modifier.fillMaxSize()) {
                        Row(Modifier.weight(1f)) {
                            Box(modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .background(theme.lightColors.primary))
                            Box(modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .background(theme.lightColors.secondary))
                        }
                        Row(Modifier.weight(1f)) {
                            Box(modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .background(theme.lightColors.tertiary))
                            Box(modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .background(theme.lightColors.surface))
                        }
                    }

                    this@Column.AnimatedVisibility(
                        visible = isSelected,
                        enter = fadeIn(animationSpec = spring()),
                        exit = fadeOut(animationSpec = spring())
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .background(Color.Black.copy(alpha = 0.4f))
                        )
                        Icon(
                            imageVector = AppIcons.Check,
                            contentDescription = stringResource(R.string.text_2d_selected, theme.name),
                            tint = Color.White,
                            modifier = Modifier.size(32.dp)
                        )
                    }
                }

                Text(
                    text = theme.name,
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                    color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                )
            }
        }
    }
}

@Composable
private fun SystemThemeOption(isSelected: Boolean, onClick: () -> Unit) {
    val borderColor by animateColorAsState(
        targetValue = if (isSelected) MaterialTheme.colorScheme.primary else Color.Transparent,
        animationSpec = spring(stiffness = Spring.StiffnessMedium),
        label = "borderColor"
    )

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier
            .clip(RoundedCornerShape(12.dp))
            .clickable(onClick = onClick)
            .padding(vertical = 4.dp)
    ) {
        Box(
            modifier = Modifier
                .size(64.dp)
                .clip(CircleShape)
                .border(
                    width = 3.dp,
                    color = borderColor,
                    shape = CircleShape
                )
                .background(MaterialTheme.colorScheme.surfaceVariant),
            contentAlignment = Alignment.Center
        ) {
            // Icon representing the system/wallpaper theme
            Icon(
                imageVector = AppIcons.Wallpaper,
                contentDescription = stringResource(R.string.system_theme),
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(32.dp)
            )

            this@Column.AnimatedVisibility(
                visible = isSelected,
                enter = fadeIn(animationSpec = spring()),
                exit = fadeOut(animationSpec = spring())
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.4f))
                )
                Icon(
                    imageVector = AppIcons.Check,
                    contentDescription = stringResource(R.string.text_2d_selected, stringResource(R.string.system_theme)),
                    tint = Color.White,
                    modifier = Modifier.size(32.dp)
                )
            }
        }

        Text(
            text = stringResource(R.string.label_system),
            style = MaterialTheme.typography.labelMedium,
            fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
            color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
        )
    }
}


@SuppressLint("LocalContextResourcesRead", "DiscouragedApi")
@Composable
private fun FontPicker(selectedFontName: String, onFontSelected: (FontStyle) -> Unit) {
    val context = LocalContext.current
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        AllFonts.forEach { font ->
            val isSelected = font.name == selectedFontName
            val fontFamily = if (font.name == "default") {
                FontFamily.Default
            } else {
                val fontResId = context.resources.getIdentifier(font.fileName, "font", context.packageName)
                if (fontResId != 0) FontFamily(Font(resId = fontResId)) else FontFamily.Default
            }

            val displayText = if (font.name == "default") {
                stringResource(R.string.system_default_font)
            } else {
                stringResource(R.string.d_the_quick_brown_fox_jumps_over_the_lazy_dog, font.name)
            }

            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onFontSelected(font) },
                shape = RoundedCornerShape(12.dp),
                border = if (isSelected) BorderStroke(2.dp, MaterialTheme.colorScheme.primary) else BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant)
            ) {
                Text(
                    text = displayText,
                    style = MaterialTheme.typography.bodyLarge.copy(fontFamily = fontFamily),
                    modifier = Modifier.padding(16.dp),
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}

@ThemePreviews
@Composable
private fun LayoutOptionsScreenPreview() {
    val mockNavController = NavController(LocalContext.current)
    LayoutOptionsScreen(navController = mockNavController)
}