package com.tt.honeyDue.ui.screens.theme

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.platform.HapticFeedbackType
import com.tt.honeyDue.platform.rememberHapticFeedback
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.ui.theme.AppThemes
import com.tt.honeyDue.ui.theme.ThemeColors
import com.tt.honeyDue.ui.theme.ThemeManager
import com.tt.honeyDue.ui.theme.isDynamicColorSupported

/**
 * ThemeSelectionScreen — full-screen theme picker matching iOS
 * `iosApp/iosApp/Profile/ThemeSelectionView.swift`.
 *
 * Behavior:
 *  - Lists all 11 themes from [ThemeManager.getAllThemes].
 *  - Each row shows a preview of the theme's primary/secondary/accent
 *    swatches, the theme name, description, and a checkmark on the
 *    currently selected theme.
 *  - Tapping a row calls [ThemeSelectionScreenState.onThemeTap] which
 *    auto-applies the theme via [ThemeManager.setTheme] (matches iOS —
 *    there is no explicit Apply button; the toolbar "Done" button only
 *    dismisses).
 *  - A live preview header at the top reacts to the selected theme using
 *    [ThemeManager.currentTheme] so the user sees the change before
 *    confirming.
 *  - Tapping the back/Done button calls the provided `onNavigateBack`.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ThemeSelectionScreen(
    onNavigateBack: () -> Unit,
) {
    val haptics = rememberHapticFeedback()
    val currentTheme by remember { derivedStateOf { ThemeManager.currentTheme } }
    val useDynamicColor by remember { derivedStateOf { ThemeManager.useDynamicColor } }
    val dynamicColorSupported = remember { isDynamicColorSupported() }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "Appearance",
                        fontWeight = FontWeight.SemiBold,
                    )
                },
                navigationIcon = {
                    IconButton(onClick = {
                        ThemeSelectionScreenState.onConfirm(onBack = onNavigateBack)
                    }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = MaterialTheme.colorScheme.primary,
                        )
                    }
                },
                actions = {
                    TextButton(onClick = {
                        ThemeSelectionScreenState.onConfirm(onBack = onNavigateBack)
                    }) {
                        Text(
                            text = "Done",
                            fontWeight = FontWeight.SemiBold,
                            color = MaterialTheme.colorScheme.primary,
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                ),
            )
        },
    ) { paddingValues: PaddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.md),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.md),
        ) {
            item {
                LivePreviewHeader(theme = currentTheme)
            }

            if (dynamicColorSupported) {
                item {
                    DynamicColorToggleRow(
                        enabled = useDynamicColor,
                        onToggle = { newValue ->
                            haptics.perform(HapticFeedbackType.Selection)
                            ThemeSelectionScreenState.onDynamicColorToggle(newValue)
                        },
                    )
                }
            }

            items(ThemeManager.getAllThemes(), key = { it.id }) { theme ->
                ThemeRowCard(
                    theme = theme,
                    isSelected = theme.id == currentTheme.id && !useDynamicColor,
                    dimmed = useDynamicColor,
                    onClick = {
                        haptics.perform(HapticFeedbackType.Selection)
                        ThemeSelectionScreenState.onThemeTap(theme.id)
                    },
                )
            }

            item {
                Spacer(modifier = Modifier.height(AppSpacing.lg))
            }
        }
    }
}

/**
 * Live preview card at the top of the screen — a miniature header that
 * uses the selected theme's colors directly (not MaterialTheme) so the
 * preview updates instantly regardless of the ambient theme.
 */
@Composable
private fun LivePreviewHeader(theme: ThemeColors) {
    val isDark = isSystemInDarkTheme()
    val primary = if (isDark) theme.darkPrimary else theme.lightPrimary
    val backgroundSecondary = if (isDark) theme.darkBackgroundSecondary else theme.lightBackgroundSecondary
    val textPrimary = if (isDark) theme.darkTextPrimary else theme.lightTextPrimary
    val textSecondary = if (isDark) theme.darkTextSecondary else theme.lightTextSecondary
    val textOnPrimary = if (isDark) theme.darkTextOnPrimary else theme.lightTextOnPrimary

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(AppRadius.lg))
            .background(backgroundSecondary)
            .padding(AppSpacing.lg),
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
            ) {
                Box(
                    modifier = Modifier
                        .size(36.dp)
                        .clip(RoundedCornerShape(AppRadius.md))
                        .background(primary),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        text = "Aa",
                        color = textOnPrimary,
                        fontWeight = FontWeight.Bold,
                    )
                }
                Column {
                    Text(
                        text = theme.displayName,
                        fontWeight = FontWeight.SemiBold,
                        color = textPrimary,
                    )
                    Text(
                        text = theme.description,
                        color = textSecondary,
                        style = MaterialTheme.typography.bodySmall,
                    )
                }
            }
        }
    }
}

/**
 * Material You (dynamic color) opt-in row. Only shown on Android 12+ where
 * wallpaper-derived colors are available. Toggling on causes [HoneyDueTheme]
 * to ignore the curated theme list and use the system `dynamicLightColorScheme`.
 */
@Composable
private fun DynamicColorToggleRow(
    enabled: Boolean,
    onToggle: (Boolean) -> Unit,
) {
    StandardCard(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onToggle(!enabled) },
        contentPadding = AppSpacing.md,
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = "Use system colors",
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface,
                )
                Text(
                    text = "Follow Android 12+ Material You (wallpaper colors)",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
            Switch(
                checked = enabled,
                onCheckedChange = onToggle,
            )
        }
    }
}

@Composable
private fun ThemeRowCard(
    theme: ThemeColors,
    isSelected: Boolean,
    dimmed: Boolean = false,
    onClick: () -> Unit,
) {
    val isDark = isSystemInDarkTheme()
    val swatchPrimary = if (isDark) theme.darkPrimary else theme.lightPrimary
    val swatchSecondary = if (isDark) theme.darkSecondary else theme.lightSecondary
    val swatchAccent = if (isDark) theme.darkAccent else theme.lightAccent

    StandardCard(
        modifier = Modifier
            .fillMaxWidth()
            .then(if (dimmed) Modifier.alpha(0.4f) else Modifier)
            .clickable(enabled = !dimmed, onClick = onClick)
            .then(
                if (isSelected) {
                    Modifier.border(
                        width = 2.dp,
                        color = MaterialTheme.colorScheme.primary,
                        shape = RoundedCornerShape(AppRadius.md),
                    )
                } else {
                    Modifier
                }
            ),
        contentPadding = AppSpacing.md,
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
        ) {
            // Swatch group
            Row(
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.xs),
            ) {
                Swatch(color = swatchPrimary)
                Swatch(color = swatchSecondary)
                Swatch(color = swatchAccent)
            }

            Column(
                modifier = Modifier
                    .padding(start = AppSpacing.xs),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.xs),
            ) {
                Text(
                    text = theme.displayName,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface,
                )
                Text(
                    text = theme.description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }

            Spacer(modifier = Modifier.weight(1f))

            if (isSelected) {
                Box(
                    modifier = Modifier
                        .size(28.dp)
                        .clip(CircleShape)
                        .background(
                            MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
                        ),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = "Selected",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(16.dp),
                    )
                }
            }
        }
    }
}

@Composable
private fun Swatch(color: Color) {
    Box(
        modifier = Modifier
            .size(24.dp)
            .clip(CircleShape)
            .background(color)
            .border(
                width = 1.dp,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.1f),
                shape = CircleShape,
            ),
    )
}

/**
 * State helper for [ThemeSelectionScreen].
 *
 * Pulled out as a plain object so the behavior is unit-testable in
 * `commonTest` without standing up the Compose recomposer (see
 * `ThemeSelectionScreenTest`). Production composables call into these
 * helpers so the code under test is identical to the code that ships.
 */
object ThemeSelectionScreenState {

    /**
     * Called when the user taps a theme row. Updates the app's theme
     * and emits analytics — mirrors iOS `selectTheme(_:)` which updates
     * `themeManager.currentTheme` and tracks `.themeChanged(...)`.
     */
    fun onThemeTap(themeId: String) {
        val theme = AppThemes.getThemeById(themeId)
        ThemeManager.setTheme(theme)
        PostHogAnalytics.capture(
            AnalyticsEvents.THEME_CHANGED,
            mapOf("theme" to theme.id),
        )
    }

    /**
     * Called when the user toggles the Material You (dynamic color) switch.
     * Persists the flag via [ThemeManager.setUseDynamicColor] and emits an
     * analytics event so we can track Material You adoption.
     */
    fun onDynamicColorToggle(enabled: Boolean) {
        ThemeManager.applyDynamicColor(enabled)
        PostHogAnalytics.capture(
            AnalyticsEvents.THEME_CHANGED,
            mapOf(
                "theme" to ThemeManager.currentTheme.id,
                "dynamic_color" to enabled,
            ),
        )
    }

    /**
     * Called when the user confirms (Done / back). iOS behavior is
     * simply to dismiss — the theme has already been applied on tap.
     */
    fun onConfirm(onBack: () -> Unit) {
        onBack()
    }
}
