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

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.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.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.UserSummaryDto
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarFloatingMainMenu
import com.seven.ikar.kotlin.ui.IkarHeaderIconBubble
import com.seven.ikar.kotlin.ui.IkarMainMenuTab
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSearchCard
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarSettingRow
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import java.util.Locale

@Composable
fun SettingsScreen(
    state: SettingsUiState,
    onChatsClick: () -> Unit,
    onContactsClick: () -> Unit,
    onSettingsClick: () -> Unit,
    onProfileClick: () -> Unit,
    onAccountClick: () -> Unit,
    onChatSettingsClick: () -> Unit,
    onPrivacyClick: () -> Unit,
    onNotificationsClick: () -> Unit,
    onBotsClick: () -> Unit,
    onFoldersClick: () -> Unit,
    onDevicesClick: () -> Unit,
    onUpdatesClick: () -> Unit,
    onDataStorageClick: () -> Unit,
    onThemeClick: () -> Unit,
    onLanguageClick: () -> Unit,
    onProxyClick: () -> Unit,
    onStoriesClick: () -> Unit
) {
    var isSearchVisible by rememberSaveable { mutableStateOf(false) }
    var searchQuery by rememberSaveable { mutableStateOf("") }

    val settingsEntries = remember(
        onAccountClick,
        onChatSettingsClick,
        onPrivacyClick,
        onNotificationsClick,
        onBotsClick,
        onFoldersClick,
        onDevicesClick,
        onUpdatesClick,
        onDataStorageClick,
        onThemeClick,
        onLanguageClick,
        onProxyClick,
        onStoriesClick
    ) {
        listOf(
            SettingsEntryModel(
                title = "Аккаунт",
                subtitle = "Телефон, имя и описание профиля",
                backgroundColor = Color(0xFFE6F1FD),
                accentColor = TelegramBlue,
                letter = "А",
                onClick = onAccountClick,
                keywords = listOf("телефон", "номер", "имя", "username", "описание", "профиль")
            ),
            SettingsEntryModel(
                title = "Настройки чатов",
                subtitle = "Обои, список чатов, жесты и медиа",
                backgroundColor = Color(0xFFFFF8ECD8),
                accentColor = Color(0xFFD7812B),
                letter = "Ч",
                onClick = onChatSettingsClick,
                keywords = listOf(
                    "обои",
                    "список чатов",
                    "жесты",
                    "медиа",
                    "текст сообщений",
                    "углы",
                    "свайп",
                    "встроенный браузер",
                    "анимации",
                    "direct share",
                    "отправка по enter",
                    "микрофон",
                    "18+"
                )
            ),
            SettingsEntryModel(
                title = "Конфиденциальность",
                subtitle = "Контакты и отображение имён в чатах",
                backgroundColor = Color(0xFFE9F7E5),
                accentColor = Color(0xFF44A948),
                letter = "К",
                onClick = onPrivacyClick,
                keywords = listOf("контакты", "имена", "приватность", "конфиденциальность")
            ),
            SettingsEntryModel(
                title = "Уведомления и звуки",
                subtitle = "Звуки, звонки и счётчик сообщений",
                backgroundColor = Color(0xFFFDE8EA),
                accentColor = Color(0xFFDC4E5C),
                letter = "У",
                onClick = onNotificationsClick,
                keywords = listOf("уведомления", "звук", "звонки", "push", "счётчик")
            ),
            SettingsEntryModel(
                title = "Обновление приложения",
                subtitle = "Проверка новой версии Икара и установка из Argus",
                backgroundColor = Color(0xFFE8F3FF),
                accentColor = TelegramBlue,
                letter = "О",
                onClick = onUpdatesClick,
                keywords = listOf("обновление", "version", "apk", "argus", "релиз", "установка")
            ),
            SettingsEntryModel(
                title = "Боты",
                subtitle = "Создание, токены и команды API ботов",
                backgroundColor = Color(0xFFEAF4FF),
                accentColor = TelegramBlue,
                letter = "Б",
                onClick = onBotsClick,
                keywords = listOf("bot api", "токен", "команды", "бот", "боты")
            ),
            SettingsEntryModel(
                title = "Данные и память",
                subtitle = "Кэш и локальные медиафайлы",
                backgroundColor = Color(0xFFEAF0FD),
                accentColor = Color(0xFF4B76E4),
                letter = "Д",
                onClick = onDataStorageClick,
                keywords = listOf("кэш", "память", "данные", "медиафайлы", "хранилище")
            ),
            SettingsEntryModel(
                title = "Папки с чатами",
                subtitle = "Стартовый фильтр для списка чатов",
                backgroundColor = Color(0xFFEEF5FD),
                accentColor = Color(0xFF5293F1),
                letter = "П",
                onClick = onFoldersClick,
                keywords = listOf("папки", "фильтр", "список чатов", "архив")
            ),
            SettingsEntryModel(
                title = "Устройства",
                subtitle = "Устройства уведомлений и их состояние",
                backgroundColor = Color(0xFFEAF7FB),
                accentColor = Color(0xFF49A8C2),
                letter = "У",
                onClick = onDevicesClick,
                keywords = listOf("устройства", "push", "сессии", "авторизация")
            ),
            SettingsEntryModel(
                title = "Энергосбережение",
                subtitle = "Фоновое обновление и прогрев превью",
                backgroundColor = Color(0xFFFFF1E6),
                accentColor = Color(0xFFD7812B),
                letter = "Э",
                onClick = null,
                keywords = listOf("батарея", "энергосбережение", "фон", "превью")
            ),
            SettingsEntryModel(
                title = "Истории",
                subtitle = "Лента, редактор, срок жизни и защищённые истории",
                backgroundColor = Color(0xFFEAF4FF),
                accentColor = TelegramBlue,
                letter = "И",
                onClick = onStoriesClick,
                keywords = listOf("stories", "истории", "сторис", "композер", "story")
            ),
            SettingsEntryModel(
                title = "Тема",
                subtitle = "Тема, акцент, эмодзи и анимированные фоны",
                backgroundColor = Color(0xFFE9F7E5),
                accentColor = Color(0xFF44A948),
                letter = "Т",
                onClick = onThemeClick,
                keywords = listOf("theme", "тема", "ночная", "оформление")
            ),
            SettingsEntryModel(
                title = "Язык",
                subtitle = "Русский",
                backgroundColor = Color(0xFFF3EAFF),
                accentColor = Color(0xFFA25FE0),
                letter = "Я",
                onClick = onLanguageClick,
                keywords = listOf("язык", "русский", "локаль")
            ),
            SettingsEntryModel(
                title = "Прокси",
                subtitle = "SOCKS/MTProto/HTTP профиль подключения",
                backgroundColor = Color(0xFFEAF7FB),
                accentColor = Color(0xFF49A8C2),
                letter = "П",
                onClick = onProxyClick,
                keywords = listOf("proxy", "прокси", "socks", "mtproto", "сеть")
            )
        )
    }

    val visibleEntries = remember(settingsEntries, searchQuery) {
        filterSettingsEntries(settingsEntries, searchQuery)
    }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 18.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            SettingsProfileHeader(
                user = state.session?.user,
                isSearchVisible = isSearchVisible,
                onAccountClick = onAccountClick,
                onSearchClick = {
                    if (isSearchVisible) {
                        if (searchQuery.isBlank()) {
                            isSearchVisible = false
                        } else {
                            searchQuery = ""
                        }
                    } else {
                        isSearchVisible = true
                    }
                }
            )

            if (isSearchVisible) {
                IkarSearchCard(
                    value = searchQuery,
                    onValueChange = { searchQuery = it },
                    placeholder = "Искать в настройках"
                )
            }

            IkarSectionCard {
                if (visibleEntries.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 18.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "Ничего не найдено",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                } else {
                    visibleEntries.forEachIndexed { index, entry ->
                        SettingsEntry(
                            title = entry.title,
                            subtitle = entry.subtitle,
                            backgroundColor = entry.backgroundColor,
                            accentColor = entry.accentColor,
                            letter = entry.letter,
                            onClick = entry.onClick
                        )
                        if (index != visibleEntries.lastIndex) {
                            IkarRowDivider()
                        }
                    }
                }
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 116.dp)
            )
        }

        IkarFloatingMainMenu(
            selectedTab = IkarMainMenuTab.Settings,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(horizontal = 8.dp, vertical = 18.dp),
            onChatsClick = onChatsClick,
            onContactsClick = onContactsClick,
            onSettingsClick = onSettingsClick,
            onProfileClick = onProfileClick
        )
    }
}

@Composable
private fun SettingsProfileHeader(
    user: UserSummaryDto?,
    isSearchVisible: Boolean,
    onAccountClick: () -> Unit,
    onSearchClick: () -> Unit
) {
    val profileName = user?.displayName?.takeIf { it.isNotBlank() }
        ?: user?.username?.takeIf { it.isNotBlank() }?.let { "@$it" }
        ?: "Профиль"
    val phoneText = user?.phoneNumber?.takeIf { it.isNotBlank() }
        ?: user?.username?.takeIf { it.isNotBlank() }?.let { "@$it" }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(enabled = user != null, onClick = onAccountClick)
            .padding(top = 8.dp, bottom = 4.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 52.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            AvatarView(
                imageUrl = user?.avatarPath,
                title = profileName,
                size = 104.dp
            )
            Text(
                text = profileName,
                style = MaterialTheme.typography.displayLarge,
                fontWeight = FontWeight.SemiBold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            if (!phoneText.isNullOrBlank()) {
                Text(
                    text = phoneText,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }

        IkarHeaderIconBubble(
            modifier = Modifier.align(Alignment.TopEnd),
            onClick = onSearchClick
        ) {
            Icon(
                imageVector = if (isSearchVisible) Icons.Outlined.Close else Icons.Outlined.Search,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSurface
            )
        }
    }
}

private data class SettingsEntryModel(
    val title: String,
    val subtitle: String,
    val backgroundColor: Color,
    val accentColor: Color,
    val letter: String,
    val onClick: (() -> Unit)?,
    val keywords: List<String>
)

private data class RankedSettingsEntry(
    val entry: SettingsEntryModel,
    val rank: Int,
    val originalIndex: Int
)

private fun filterSettingsEntries(
    entries: List<SettingsEntryModel>,
    query: String
): List<SettingsEntryModel> {
    val normalizedQuery = query.trim().lowercase(Locale.ROOT)
    if (normalizedQuery.isBlank()) {
        return entries
    }

    return entries.mapIndexedNotNull { index, entry ->
        val rank = entry.matchRank(normalizedQuery) ?: return@mapIndexedNotNull null
        RankedSettingsEntry(entry = entry, rank = rank, originalIndex = index)
    }.sortedWith(compareBy<RankedSettingsEntry> { it.rank }.thenBy { it.originalIndex })
        .map { it.entry }
}

private fun SettingsEntryModel.matchRank(normalizedQuery: String): Int? {
    val normalizedTitle = title.lowercase(Locale.ROOT)
    val normalizedSubtitle = subtitle.lowercase(Locale.ROOT)
    val normalizedKeywords = keywords.map { it.lowercase(Locale.ROOT) }

    return when {
        normalizedTitle == normalizedQuery -> 0
        normalizedTitle.startsWith(normalizedQuery) -> 1
        normalizedTitle.contains(normalizedQuery) -> 2
        normalizedKeywords.any { it == normalizedQuery } -> 3
        normalizedKeywords.any { it.startsWith(normalizedQuery) } -> 4
        normalizedKeywords.any { it.contains(normalizedQuery) } -> 5
        normalizedSubtitle.contains(normalizedQuery) -> 6
        else -> null
    }
}

@Composable
private fun SettingsEntry(
    title: String,
    subtitle: String,
    backgroundColor: Color,
    accentColor: Color,
    letter: String,
    onClick: (() -> Unit)?
) {
    IkarSettingRow(
        title = title,
        subtitle = subtitle,
        onClick = onClick,
        leading = {
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = backgroundColor,
                shape = CircleShape
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Text(
                        text = letter,
                        style = MaterialTheme.typography.titleMedium,
                        color = accentColor,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    )
}
