package com.seven.ikar.kotlin.feature.search

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
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.ChatSearchResultDto
import com.seven.ikar.kotlin.core.model.ChatType
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.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.chatPreview
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 GlobalSearchScreen(
    state: GlobalSearchUiState,
    onBackClick: () -> Unit,
    onQueryChanged: (String) -> Unit,
    onFilterChanged: (GlobalSearchFilter) -> Unit,
    onDateFilterChanged: (GlobalSearchDateFilter) -> Unit = {},
    onResultTypeChanged: (GlobalSearchResultType) -> Unit = {},
    onAuthorFilterChanged: (String) -> Unit = {},
    onLoadMore: () -> Unit = {},
    onResultClick: (ChatSearchResultDto) -> Unit
) {
    val visibleResults = state.visibleResults
    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .padding(horizontal = 18.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            IkarSimpleHeader(title = "Глобальный поиск", onBackClick = onBackClick)

            IkarSearchCard(
                value = state.query,
                onValueChange = onQueryChanged,
                placeholder = "Поиск чатов и сообщений"
            )

            GlobalSearchFilterRow(
                selected = state.filter,
                onFilterChanged = onFilterChanged
            )

            GlobalSearchAdvancedFilters(
                selectedDate = state.dateFilter,
                selectedType = state.resultType,
                authorFilter = state.authorFilter,
                onDateFilterChanged = onDateFilterChanged,
                onResultTypeChanged = onResultTypeChanged,
                onAuthorFilterChanged = onAuthorFilterChanged
            )

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

            IkarSectionCard(modifier = Modifier.weight(1f)) {
                when {
                    state.isSearching -> {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            CircularProgressIndicator(color = TelegramBlue)
                        }
                    }

                    state.results.isEmpty() -> {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text("Ничего не найдено", style = MaterialTheme.typography.titleMedium)
                            Text(
                                "Введите текст или переключитесь на медиа, файлы или ссылки.",
                                style = MaterialTheme.typography.bodySmall,
                                color = TelegramInkMuted
                            )
                        }
                    }

                    visibleResults.isEmpty() -> {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text("Нет результатов по фильтрам", style = MaterialTheme.typography.titleMedium)
                            Text(
                                "Расширьте фильтр по дате, автору или типу.",
                                style = MaterialTheme.typography.bodySmall,
                                color = TelegramInkMuted
                            )
                        }
                    }

                    else -> {
                        LazyColumn(modifier = Modifier.fillMaxSize()) {
                            if (state.filter == GlobalSearchFilter.Media || state.resultType == GlobalSearchResultType.Attachments) {
                                visibleResults
                                    .groupBy { it.searchDateGroupLabel() }
                                    .forEach { (dateGroup, results) ->
                                        item(key = "date:$dateGroup") {
                                            Text(
                                                text = dateGroup,
                                                style = MaterialTheme.typography.labelMedium,
                                                color = TelegramInkMuted,
                                                modifier = Modifier.padding(top = 10.dp, bottom = 4.dp)
                                            )
                                        }
                                        items(results, key = { "${it.chat.id}:${it.message?.id.orEmpty()}" }) { result ->
                                            GlobalSearchResultRow(
                                                result = result,
                                                query = state.query,
                                                onClick = { onResultClick(result) }
                                            )
                                            IkarRowDivider()
                                        }
                                    }
                            } else {
                                items(visibleResults, key = { "${it.chat.id}:${it.message?.id.orEmpty()}" }) { result ->
                                    GlobalSearchResultRow(
                                        result = result,
                                        query = state.query,
                                        onClick = { onResultClick(result) }
                                    )
                                    IkarRowDivider()
                                }
                            }
                            if (state.hasMore) {
                                item(key = "load-more") {
                                    TextButton(
                                        enabled = !state.isLoadingMore,
                                        onClick = onLoadMore,
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Text(if (state.isLoadingMore) "Загрузка..." else "Показать ещё", color = TelegramBlue)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun GlobalSearchAdvancedFilters(
    selectedDate: GlobalSearchDateFilter,
    selectedType: GlobalSearchResultType,
    authorFilter: String,
    onDateFilterChanged: (GlobalSearchDateFilter) -> Unit,
    onResultTypeChanged: (GlobalSearchResultType) -> Unit,
    onAuthorFilterChanged: (String) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
            GlobalSearchDateFilter.entries.forEach { filter ->
                TextButton(onClick = { onDateFilterChanged(filter) }) {
                    Text(
                        text = filter.label(),
                        color = if (filter == selectedDate) TelegramBlue else TelegramInkMuted,
                        fontWeight = if (filter == selectedDate) FontWeight.SemiBold else FontWeight.Normal
                    )
                }
            }
        }
        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
            GlobalSearchResultType.entries.forEach { type ->
                TextButton(onClick = { onResultTypeChanged(type) }) {
                    Text(
                        text = type.label(),
                        color = if (type == selectedType) TelegramBlue else TelegramInkMuted,
                        fontWeight = if (type == selectedType) FontWeight.SemiBold else FontWeight.Normal
                    )
                }
            }
        }
        IkarSearchCard(
            value = authorFilter,
            onValueChange = onAuthorFilterChanged,
            placeholder = "Фильтр по автору"
        )
    }
}

@Composable
private fun GlobalSearchFilterRow(
    selected: GlobalSearchFilter,
    onFilterChanged: (GlobalSearchFilter) -> Unit
) {
    Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
        GlobalSearchFilter.entries.forEach { filter ->
            TextButton(onClick = { onFilterChanged(filter) }) {
                Text(
                    text = when (filter) {
                        GlobalSearchFilter.All -> "Все"
                        GlobalSearchFilter.Media -> "Медиа"
                        GlobalSearchFilter.Files -> "Файлы"
                        GlobalSearchFilter.Links -> "Ссылки"
                    },
                    color = if (filter == selected) TelegramBlue else TelegramInkMuted,
                    fontWeight = if (filter == selected) FontWeight.SemiBold else FontWeight.Normal
                )
            }
        }
    }
}

@Composable
private fun GlobalSearchResultRow(
    result: ChatSearchResultDto,
    query: String,
    onClick: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Text(
            text = highlightedText(result.chat.title, query),
            style = MaterialTheme.typography.titleMedium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Text(
            text = highlightedText(result.matchText.ifBlank { chatPreview(result.chat) }, query),
            style = MaterialTheme.typography.bodyMedium,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis
        )
        result.message?.attachments?.takeIf { it.isNotEmpty() }?.let { attachments ->
            Text(
                text = attachments.joinToString(limit = 3) { it.fileName },
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        result.botMiniAppDeepLink()?.let { deepLink ->
            TextButton(onClick = {}) {
                Text("Мини-приложение: $deepLink", color = TelegramBlue)
            }
        }
        if (result.chat.type == ChatType.Group) {
            Text(
                text = "Групповой звонок готов для голосовых и видеодействий.",
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }
    }
}

@Composable
private fun highlightedText(text: String, query: String) = buildAnnotatedString {
    val needle = query.trim()
    if (needle.length < 2) {
        append(text)
        return@buildAnnotatedString
    }

    var currentIndex = 0
    while (currentIndex < text.length) {
        val matchIndex = text.indexOf(needle, startIndex = currentIndex, ignoreCase = true)
        if (matchIndex < 0) {
            append(text.substring(currentIndex))
            break
        }
        append(text.substring(currentIndex, matchIndex))
        pushStyle(
            SpanStyle(
                color = MaterialTheme.colorScheme.primary,
                fontWeight = FontWeight.SemiBold,
                background = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f)
            )
        )
        append(text.substring(matchIndex, matchIndex + needle.length))
        pop()
        currentIndex = matchIndex + needle.length
    }
}

private fun GlobalSearchDateFilter.label(): String =
    when (this) {
        GlobalSearchDateFilter.Anytime -> "Любая дата"
        GlobalSearchDateFilter.Today -> "Сегодня"
        GlobalSearchDateFilter.ThisWeek -> "Неделя"
        GlobalSearchDateFilter.ThisMonth -> "Месяц"
    }

private fun GlobalSearchResultType.label(): String =
    when (this) {
        GlobalSearchResultType.All -> "Все типы"
        GlobalSearchResultType.Chats -> "Чаты"
        GlobalSearchResultType.Messages -> "Сообщения"
        GlobalSearchResultType.Attachments -> "Вложения"
        GlobalSearchResultType.Bots -> "Боты"
        GlobalSearchResultType.GroupCalls -> "Звонки"
    }

private fun ChatSearchResultDto.botMiniAppDeepLink(): String? {
    val bot = chat.participants.firstOrNull { it.isBot } ?: return null
    return "ikar://bot/${bot.username}?start=miniapp"
}
