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

import androidx.compose.foundation.background
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.ColumnScope
import androidx.compose.foundation.layout.Row
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.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.seven.ikar.kotlin.ui.ChatWallpaperBackground
import com.seven.ikar.kotlin.core.settings.ChatDistanceUnitOption
import com.seven.ikar.kotlin.core.settings.ChatSettingsSnapshot
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material3.Icon
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.TelegramInk
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted
import kotlin.math.roundToInt

@Composable
fun ChatSettingsScreen(
    state: ChatSettingsUiState,
    onBackClick: () -> Unit,
    onSnapshotChanged: (ChatSettingsSnapshot) -> Unit,
    onWallpaperClick: () -> 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)

            ChatSettingsSection {
                IkarSectionTitle("Оформление", modifier = Modifier.padding(bottom = 12.dp))
                SliderSettingBlock(
                    title = "Размер текста сообщений",
                    value = snapshot.messageTextSizeSp,
                    range = 14..26,
                    previewMessageTextSizeSp = snapshot.messageTextSizeSp,
                    previewBubbleCornerRadiusDp = snapshot.bubbleCornerRadiusDp,
                    wallpaperSnapshot = snapshot,
                    onValueChange = { value ->
                        onSnapshotChanged(snapshot.copy(messageTextSizeSp = value))
                    }
                )
                IkarRowDivider(startIndent = 0.dp)
                SliderSettingBlock(
                    title = "Углы блоков с сообщениями",
                    value = snapshot.bubbleCornerRadiusDp,
                    range = 4..24,
                    previewMessageTextSizeSp = snapshot.messageTextSizeSp,
                    previewBubbleCornerRadiusDp = snapshot.bubbleCornerRadiusDp,
                    wallpaperSnapshot = snapshot,
                    onValueChange = { value ->
                        onSnapshotChanged(snapshot.copy(bubbleCornerRadiusDp = value))
                    }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarValueRow(
                    title = "Изменить обои",
                    subtitle = "Выбрать фон ленты чатов из галереи или готовых вариантов.",
                    value = "Открыть",
                    onClick = onWallpaperClick,
                    leading = {
                        Icon(
                            imageVector = Icons.Outlined.Image,
                            contentDescription = null,
                            tint = TelegramBlue
                        )
                    }
                )
            }

            ChatSettingsSection {
                IkarSectionTitle("Медиафайлы и звук", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    title = "Листать медиафайлы по нажатию",
                    subtitle = "Листать нажатием у края экрана в режиме просмотра медиафайлов.",
                    checked = snapshot.mediaTapToBrowseEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(mediaTapToBrowseEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Поднести и слушать",
                    subtitle = "Переключаться на верхний динамик, когда вы подносите телефон к уху.",
                    checked = snapshot.raiseToListenEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(raiseToListenEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Поднести и говорить",
                    subtitle = "Записывать голосовое сообщение, когда вы подносите телефон к уху.",
                    checked = snapshot.raiseToTalkEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(raiseToTalkEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Пауза музыки при записи",
                    subtitle = "Останавливать музыку на время записи голосового сообщения.",
                    checked = snapshot.pauseMusicOnRecordEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(pauseMusicOnRecordEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Пауза музыки при запуске медиа",
                    subtitle = "Останавливать фоновую музыку при воспроизведении медиафайлов в чате.",
                    checked = snapshot.pauseMusicOnPlaybackEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(pauseMusicOnPlaybackEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarValueRow(
                    title = "Микрофон",
                    subtitle = "Источник записи голосовых сообщений.",
                    value = "По умолчанию",
                    enabled = false
                )
            }

            ChatSettingsSection {
                IkarSectionTitle("Прочие настройки", modifier = Modifier.padding(bottom = 12.dp))
                IkarToggleRow(
                    title = "Смена темы ночью",
                    subtitle = "Автоматически включать ночную тему по локальному сценарию.",
                    checked = snapshot.autoNightThemeEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(autoNightThemeEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Встроенный браузер",
                    subtitle = "Открывать ссылки внутри приложения, если доступен встроенный просмотр.",
                    checked = snapshot.inAppBrowserEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(inAppBrowserEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Анимации",
                    subtitle = "Использовать анимации интерфейса и медиа-переходов.",
                    checked = snapshot.animationsEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(animationsEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Прямая отправка",
                    subtitle = "Показывать недавние чаты в системном меню «Поделиться».",
                    checked = snapshot.directShareEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(directShareEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Показывать материалы 18+",
                    subtitle = "Не скрывать чувствительные медиафайлы.",
                    checked = snapshot.showSensitiveContentEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(showSensitiveContentEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarToggleRow(
                    title = "Отправка по Вводу",
                    subtitle = "Использовать действие отправки вместо перевода строки, если клавиатура поддерживает «Отправить».",
                    checked = snapshot.sendByEnterEnabled,
                    onCheckedChange = { onSnapshotChanged(snapshot.copy(sendByEnterEnabled = it)) }
                )
                IkarRowDivider(startIndent = 0.dp)
                IkarValueRow(
                    title = "Мера расстояния",
                    subtitle = "Единицы для геоданных и расстояний в интерфейсе.",
                    value = snapshot.distanceUnit.title,
                    onClick = {
                        onSnapshotChanged(snapshot.copy(distanceUnit = snapshot.distanceUnit.next()))
                    }
                )
            }

            Text(
                text = "Сбросить настройки чатов",
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable(onClick = onResetClick)
                    .padding(vertical = 4.dp),
                style = MaterialTheme.typography.titleLarge,
                color = TelegramBlue,
                fontWeight = FontWeight.SemiBold
            )
        }
    }
}

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

@Composable
private fun SliderSettingBlock(
    title: String,
    value: Int,
    range: IntRange,
    previewMessageTextSizeSp: Int,
    previewBubbleCornerRadiusDp: Int,
    wallpaperSnapshot: ChatSettingsSnapshot,
    onValueChange: (Int) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(title, style = MaterialTheme.typography.titleLarge)
            Text(
                text = value.toString(),
                style = MaterialTheme.typography.titleMedium,
                color = TelegramBlue
            )
        }
        Slider(
            value = value.toFloat(),
            onValueChange = { onValueChange(it.roundToInt().coerceIn(range.first, range.last)) },
            valueRange = range.first.toFloat()..range.last.toFloat(),
            steps = (range.last - range.first - 1).coerceAtLeast(0)
        )
        ChatStylePreview(
            messageTextSizeSp = previewMessageTextSizeSp,
            bubbleCornerRadiusDp = previewBubbleCornerRadiusDp,
            wallpaperSnapshot = wallpaperSnapshot
        )
    }
}

@Composable
private fun ChatStylePreview(
    messageTextSizeSp: Int,
    bubbleCornerRadiusDp: Int,
    wallpaperSnapshot: ChatSettingsSnapshot
) {
    val bubbleRadius = bubbleCornerRadiusDp.dp
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color(0xFFE7F6F0), RoundedCornerShape(20.dp))
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(20.dp))
        )
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Transparent, RoundedCornerShape(20.dp))
        ) {
            ChatWallpaperBackground(
                snapshot = wallpaperSnapshot,
                modifier = Modifier.fillMaxSize()
            )
        }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White.copy(alpha = 0.12f), RoundedCornerShape(20.dp))
                .padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Start
            ) {
                Text(
                    text = "Доброе утро!",
                    modifier = Modifier
                        .background(Color(0xFFFBE8EC), RoundedCornerShape(bubbleRadius))
                        .padding(horizontal = 12.dp, vertical = 8.dp),
                    style = MaterialTheme.typography.bodyLarge.copy(fontSize = messageTextSizeSp.sp),
                    color = TelegramInk
                )
            }
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End
            ) {
                Text(
                    text = "Знаю, который час?",
                    modifier = Modifier
                        .background(Color.White, RoundedCornerShape(bubbleRadius))
                        .padding(horizontal = 12.dp, vertical = 8.dp),
                    style = MaterialTheme.typography.bodyLarge.copy(fontSize = messageTextSizeSp.sp),
                    color = TelegramInk
                )
            }
        }
    }
}

@Composable
private fun BoxLine(width: Dp) {
    Row(
        modifier = Modifier
            .width(width)
            .background(Color(0xFFDCE4EA), RoundedCornerShape(999.dp))
            .padding(vertical = 2.dp)
    ) {}
}

private val ChatDistanceUnitOption.title: String
    get() = when (this) {
        ChatDistanceUnitOption.Automatic -> "Автоматически"
        ChatDistanceUnitOption.Kilometers -> "Километры"
        ChatDistanceUnitOption.Miles -> "Мили"
    }

private fun ChatDistanceUnitOption.next(): ChatDistanceUnitOption = when (this) {
    ChatDistanceUnitOption.Automatic -> ChatDistanceUnitOption.Kilometers
    ChatDistanceUnitOption.Kilometers -> ChatDistanceUnitOption.Miles
    ChatDistanceUnitOption.Miles -> ChatDistanceUnitOption.Automatic
}

