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.outlined.Campaign
import androidx.compose.material.icons.outlined.Groups
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material.icons.outlined.PersonOutline
import androidx.compose.material.icons.outlined.VolumeUp
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 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

@Composable
fun NotificationSettingsScreen(
    state: NotificationSettingsUiState,
    messageSoundOptions: List<NotificationSoundChoice>,
    onBackClick: () -> Unit,
    onSnapshotChanged: (NotificationSettingsSnapshot) -> Unit,
    onMessageSoundChanged: (NotificationSoundOption) -> Unit,
    onResetClick: () -> Unit
) {
    val snapshot = state.snapshot

    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)

            NotificationSection {
                IkarSectionTitle("Основное", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    "Уведомления",
                    "Регистрировать устройство и показывать push-уведомления.",
                    snapshot.notificationsEnabled,
                    { onSnapshotChanged(snapshot.copy(notificationsEnabled = it)) },
                    leading = { androidx.compose.material3.Icon(Icons.Outlined.Notifications, contentDescription = null, tint = TelegramInkMuted) }
                )
                IkarRowDivider(startIndent = 32.dp)
                IkarValueRow(
                    title = "Звук сообщений",
                    subtitle = "Канал уведомлений для новых сообщений.",
                    value = messageSoundOptions.firstOrNull { it.value == snapshot.messageSound }?.title ?: "По умолчанию",
                    onClick = if (messageSoundOptions.isEmpty()) null else ({
                        val currentIndex = messageSoundOptions.indexOfFirst { it.value == snapshot.messageSound }.coerceAtLeast(0)
                        val next = messageSoundOptions[(currentIndex + 1) % messageSoundOptions.size]
                        onMessageSoundChanged(next.value)
                    }),
                    leading = { androidx.compose.material3.Icon(Icons.Outlined.VolumeUp, contentDescription = null, tint = TelegramInkMuted) }
                )
            }

            NotificationSection {
                IkarSectionTitle("Уведомления из чатов", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow("Личные чаты", "Уведомления личных чатов", snapshot.privateChatsEnabled, { onSnapshotChanged(snapshot.copy(privateChatsEnabled = it)) }, leading = { androidx.compose.material3.Icon(Icons.Outlined.PersonOutline, contentDescription = null, tint = TelegramInkMuted) })
                IkarRowDivider(startIndent = 32.dp)
                IkarToggleRow("Группы", "Уведомления групп", snapshot.groupsEnabled, { onSnapshotChanged(snapshot.copy(groupsEnabled = it)) }, leading = { androidx.compose.material3.Icon(Icons.Outlined.Groups, contentDescription = null, tint = TelegramInkMuted) })
                IkarRowDivider(startIndent = 32.dp)
                IkarToggleRow("Каналы", "Уведомления каналов", snapshot.channelsEnabled, { onSnapshotChanged(snapshot.copy(channelsEnabled = it)) }, leading = { androidx.compose.material3.Icon(Icons.Outlined.Campaign, contentDescription = null, tint = TelegramInkMuted) })
                IkarRowDivider(startIndent = 32.dp)
                IkarToggleRow("Реакции", "Реакции на сообщения", snapshot.reactionsEnabled, { onSnapshotChanged(snapshot.copy(reactionsEnabled = it)) }, leading = { Text("♥", color = TelegramBlue, style = MaterialTheme.typography.titleMedium) })
            }

            NotificationSection {
                IkarSectionTitle("Счётчик сообщений", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow("Показывать счётчик", "Индикатор на значке «Чаты» в нижнем меню.", snapshot.showBadge, { onSnapshotChanged(snapshot.copy(showBadge = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Чаты без уведомлений", "Включать в общий счётчик", snapshot.includeMutedChatsInBadge, { onSnapshotChanged(snapshot.copy(includeMutedChatsInBadge = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Число сообщений", "Показывать сумму сообщений вместо числа чатов.", snapshot.countMessagesInBadge, { onSnapshotChanged(snapshot.copy(countMessagesInBadge = it)) })
            }

            NotificationSection {
                IkarSectionTitle("В приложении", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow("Звук", "Звук всплывающих уведомлений", snapshot.inAppSoundEnabled, { onSnapshotChanged(snapshot.copy(inAppSoundEnabled = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Вибросигнал", "Вибрация внутри приложения", snapshot.inAppVibrationEnabled, { onSnapshotChanged(snapshot.copy(inAppVibrationEnabled = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Показывать текст", "Текст во всплывающем окне", snapshot.inAppShowTextEnabled, { onSnapshotChanged(snapshot.copy(inAppShowTextEnabled = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Звук в чате", "Сигнал в открытом чате", snapshot.soundInActiveChatEnabled, { onSnapshotChanged(snapshot.copy(soundInActiveChatEnabled = it)) })
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow("Всплывающие окна", "Показывать поверх приложения", snapshot.popupWindowsEnabled, { onSnapshotChanged(snapshot.copy(popupWindowsEnabled = it)) })
            }

            NotificationSection {
                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 NotificationSection(
    content: @Composable ColumnScope.() -> Unit
) {
    IkarSectionCard {
        Column(content = content)
    }
}
