package com.seven.ikar.kotlin.feature.chatinfo

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.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.MessageDto
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.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.formatLastActivity
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 ChatMaterialsScreen(
    state: ChatMaterialsUiState,
    onBackClick: () -> Unit,
    onLoadMore: () -> Unit,
    onMessageClick: (MessageDto) -> Unit
) {
    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 = state.filter.title, onBackClick = onBackClick)

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

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

                    state.messages.isEmpty() -> {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Text("Пока пусто", style = MaterialTheme.typography.titleMedium)
                            Text(
                                emptySubtitle(state.filter),
                                style = MaterialTheme.typography.bodySmall,
                                color = TelegramInkMuted
                            )
                        }
                    }

                    else -> {
                        LazyColumn(modifier = Modifier.fillMaxSize()) {
                            items(state.messages, key = { it.id }) { message ->
                                ChatMaterialRow(
                                    message = message,
                                    filter = state.filter,
                                    onClick = { onMessageClick(message) }
                                )
                                IkarRowDivider(startIndent = 0.dp)
                            }
                            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 ChatMaterialRow(
    message: MessageDto,
    filter: ChatMaterialFilter,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.Top
    ) {
        Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
            Text(
                text = message.displayAuthorName ?: message.sender.displayName,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.SemiBold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = materialPreview(message, filter),
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            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
                )
            }
        }
        Text(
            text = formatLastActivity(message.sentAt),
            style = MaterialTheme.typography.bodySmall,
            color = TelegramInkMuted
        )
    }
}

private fun materialPreview(message: MessageDto, filter: ChatMaterialFilter): String =
    when {
        message.text.isNotBlank() -> message.text
        filter == ChatMaterialFilter.Pinned -> "Закреплённое сообщение"
        message.attachments.isNotEmpty() -> message.attachments.first().fileName
        else -> "Сообщение"
    }

private fun emptySubtitle(filter: ChatMaterialFilter): String =
    when (filter) {
        ChatMaterialFilter.Media -> "В этом чате пока нет фото или видео."
        ChatMaterialFilter.Files -> "В этом чате пока нет файлов."
        ChatMaterialFilter.Links -> "В этом чате пока нет ссылок."
        ChatMaterialFilter.Voice -> "В этом чате пока нет голосовых сообщений."
        ChatMaterialFilter.Pinned -> "В этом чате пока нет закреплённых сообщений."
    }
