package com.seven.ikar.kotlin.feature.folders

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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
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.ChatFolderDto
import com.seven.ikar.kotlin.core.model.ChatSummaryDto
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.IkarSectionTitle
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 ChatFoldersScreen(
    state: ChatFoldersUiState,
    onBackClick: () -> Unit,
    onRefreshClick: () -> Unit,
    onNewFolderKeyChanged: (String) -> Unit,
    onFolderSelected: (String?) -> Unit,
    onChatToggled: (String) -> Unit,
    onAssignSelected: () -> Unit,
    onClearSelected: () -> Unit
) {
    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)

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

            if (state.isLoading && state.chats.isEmpty()) {
                CircularProgressIndicator(color = TelegramBlue)
            }

            IkarSectionCard {
                IkarSectionTitle("Папки", modifier = Modifier.padding(bottom = 8.dp))
                FolderChipRow(
                    folders = state.folders,
                    selectedFolderKey = state.selectedFolderKey,
                    onFolderSelected = onFolderSelected
                )
                IkarSearchCard(
                    value = state.newFolderKey,
                    onValueChange = onNewFolderKeyChanged,
                    placeholder = "новая-папка"
                )
                Text(
                    text = "Выберите чаты ниже, введите ключ папки и назначьте. Пустое назначение убирает чат из пользовательских папок.",
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }

            IkarSectionCard {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IkarSectionTitle("Чаты (выбрано: ${state.selectedChatIds.size})")
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        TextButton(enabled = !state.isSaving, onClick = onClearSelected) {
                            Text("Очистить")
                        }
                        TextButton(enabled = !state.isSaving, onClick = onAssignSelected) {
                            Text(if (state.isSaving) "Сохранение..." else "Назначить")
                        }
                    }
                }

                state.chats.forEachIndexed { index, chat ->
                    FolderChatRow(
                        chat = chat,
                        checked = state.selectedChatIds.contains(chat.id),
                        onClick = { onChatToggled(chat.id) }
                    )
                    if (index != state.chats.lastIndex) {
                        IkarRowDivider(startIndent = 42.dp)
                    }
                }
            }

            TextButton(onClick = onRefreshClick) {
                Text("Обновить")
            }
        }
    }
}

@Composable
private fun FolderChipRow(
    folders: List<ChatFolderDto>,
    selectedFolderKey: String?,
    onFolderSelected: (String?) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        folders.forEach { folder ->
            TextButton(onClick = { onFolderSelected(folder.key.takeUnless { it in BuiltInFolderKeys }) }) {
                Text(
                    text = "${folder.title} (${folder.totalCount})",
                    color = if (folder.key == selectedFolderKey) TelegramBlue else MaterialTheme.colorScheme.onSurface,
                    fontWeight = if (folder.key == selectedFolderKey) FontWeight.SemiBold else FontWeight.Normal
                )
            }
        }
    }
}

@Composable
private fun FolderChatRow(
    chat: ChatSummaryDto,
    checked: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 10.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Checkbox(checked = checked, onCheckedChange = { onClick() })
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = chat.title,
                style = MaterialTheme.typography.titleMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = listOfNotNull(chat.folderKey?.let { "папка: $it" }, chatPreview(chat).takeIf { it.isNotBlank() })
                    .joinToString(" • "),
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

private val BuiltInFolderKeys = setOf("all", "unread", "pinned", "archive")
