package com.seven.ikar.kotlin.feature.settings

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.VolumeUp
import androidx.compose.material.icons.outlined.ChatBubbleOutline
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.push.ChatNotificationSettingsSnapshot
import com.seven.ikar.kotlin.core.push.NotificationPreferenceCatalog
import com.seven.ikar.kotlin.core.push.NotificationSettingsSnapshot
import com.seven.ikar.kotlin.core.push.NotificationSoundChoice
import com.seven.ikar.kotlin.core.push.NotificationSoundOption
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarSectionTitle
import com.seven.ikar.kotlin.ui.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.IkarToggleRow
import com.seven.ikar.kotlin.ui.IkarValueRow
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramDanger
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

data class ChatNotificationSettingsUiState(
    val chatId: String,
    val chatTitle: String,
    val snapshot: ChatNotificationSettingsSnapshot,
    val globalSnapshot: NotificationSettingsSnapshot,
    val errorMessage: String? = null,
    val infoMessage: String? = null
)

class ChatNotificationSettingsViewModel(
    private val container: AppContainer,
    private val chatId: String,
    chatTitle: String
) : ViewModel() {
    private val _uiState = MutableStateFlow(
        ChatNotificationSettingsUiState(
            chatId = chatId,
            chatTitle = chatTitle,
            snapshot = container.pushSettings.loadChatNotificationSnapshot(chatId),
            globalSnapshot = container.pushSettings.loadSnapshot()
        )
    )
    val uiState: StateFlow<ChatNotificationSettingsUiState> = _uiState.asStateFlow()

    val messageSoundOptions: List<NotificationSoundChoice> = NotificationPreferenceCatalog.messageSoundChoices

    fun updateSnapshot(transform: (ChatNotificationSettingsSnapshot) -> ChatNotificationSettingsSnapshot) {
        val nextSnapshot = transform(_uiState.value.snapshot)
        container.pushSettings.saveChatNotificationSnapshot(chatId, nextSnapshot)
        _uiState.value = _uiState.value.copy(
            snapshot = nextSnapshot,
            infoMessage = null,
            errorMessage = null
        )
    }

    fun setMessageSound(value: NotificationSoundOption?) = updateSnapshot { it.copy(messageSound = value) }

    fun reset() {
        container.pushSettings.resetChatNotificationPreferences(chatId)
        _uiState.value = _uiState.value.copy(
            snapshot = container.pushSettings.loadChatNotificationSnapshot(chatId),
            infoMessage = "Для этого чата снова используются общие настройки.",
            errorMessage = null
        )
    }
}

@Composable
fun ChatNotificationSettingsScreen(
    state: ChatNotificationSettingsUiState,
    messageSoundOptions: List<NotificationSoundChoice>,
    onBackClick: () -> Unit,
    onSnapshotChanged: (ChatNotificationSettingsSnapshot) -> Unit,
    onMessageSoundChanged: (NotificationSoundOption?) -> Unit,
    onResetClick: () -> Unit
) {
    val snapshot = state.snapshot
    val global = state.globalSnapshot
    val effectiveNotificationsEnabled = snapshot.notificationsEnabled ?: global.notificationsEnabled
    val effectiveShowPreview = snapshot.showMessagePreview ?: global.inAppShowTextEnabled
    val effectivePopupWindows = snapshot.popupWindowsEnabled ?: global.popupWindowsEnabled
    val effectiveSoundInActiveChat = snapshot.soundInActiveChatEnabled ?: global.soundInActiveChatEnabled

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            IkarSimpleHeader(title = "Уведомления чата", onBackClick = onBackClick)

            ChatNotificationSection {
                val chatLabel = state.chatTitle.ifBlank { "Текущий чат" }
                IkarSectionTitle("Для этого чата", modifier = Modifier.padding(bottom = 12.dp))
                Text(
                    text = chatLabel,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.padding(bottom = 2.dp)
                )
                Text(
                    text = "Изменения применяются сразу.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = TelegramInkMuted,
                    modifier = Modifier.padding(bottom = 10.dp)
                )
                IkarToggleRow(
                    title = "Уведомления",
                    subtitle = overrideModeLabel(snapshot.notificationsEnabled),
                    checked = effectiveNotificationsEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(notificationsEnabled = it)) },
                    leading = { Icon(Icons.Outlined.Notifications, contentDescription = null, tint = TelegramInkMuted) }
                )
                IkarRowDivider(startIndent = 32.dp)
                IkarValueRow(
                    title = "Звук сообщений",
                    subtitle = overrideModeLabel(snapshot.messageSound),
                    value = soundCurrentLabel(snapshot.messageSound, global.messageSound, messageSoundOptions),
                    onClick = {
                        val values = listOf<NotificationSoundOption?>(null) + messageSoundOptions.map { it.value }
                        val currentIndex = values.indexOf(snapshot.messageSound).coerceAtLeast(0)
                        onMessageSoundChanged(values[(currentIndex + 1) % values.size])
                    },
                    leading = { Icon(Icons.AutoMirrored.Outlined.VolumeUp, contentDescription = null, tint = TelegramInkMuted) }
                )
            }

            ChatNotificationSection {
                IkarSectionTitle("Поведение", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    title = "Показывать текст",
                    subtitle = overrideModeLabel(snapshot.showMessagePreview),
                    checked = effectiveShowPreview,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(showMessagePreview = it)) },
                    leading = { Icon(Icons.Outlined.ChatBubbleOutline, contentDescription = null, tint = TelegramInkMuted) }
                )
                IkarRowDivider(startIndent = 32.dp)
                IkarToggleRow(
                    title = "Всплывающие окна",
                    subtitle = overrideModeLabel(snapshot.popupWindowsEnabled),
                    checked = effectivePopupWindows,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(popupWindowsEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Звук в чате",
                    subtitle = overrideModeLabel(snapshot.soundInActiveChatEnabled),
                    checked = effectiveSoundInActiveChat,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(soundInActiveChatEnabled = it)) }
                )
            }

            ChatNotificationSection {
                IkarSectionTitle("Сброс", modifier = Modifier.padding(bottom = 12.dp))
                Text(
                    "Использовать общие настройки",
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp)
                        .clickable(onClick = onResetClick),
                    style = MaterialTheme.typography.titleLarge
                )
                Text(
                    "Вернуть все пункты этого экрана к общим настройкам.",
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }

            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodyMedium)
            }
            state.infoMessage?.let {
                Text(it, color = TelegramBlue, style = MaterialTheme.typography.bodyMedium)
            }
        }
    }
}

@Composable
private fun ChatNotificationSection(
    content: @Composable ColumnScope.() -> Unit
) {
    IkarSectionCard {
        Column(content = content)
    }
}

private fun overrideModeLabel(value: Any?): String =
    if (value == null) "Общие настройки" else "Персонально"

private fun soundCurrentLabel(
    value: NotificationSoundOption?,
    globalValue: NotificationSoundOption,
    options: List<NotificationSoundChoice>
): String {
    val currentValue = value ?: globalValue
    return soundTitle(currentValue, options)
}

private fun soundTitle(value: NotificationSoundOption, options: List<NotificationSoundChoice>): String =
    options.firstOrNull { it.value == value }?.title ?: "По умолчанию"
