package ru.forbion.f7cloud.feature.talk

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7PrimaryButton
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton
import ru.forbion.f7cloud.core.designsystem.F7TextButton

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TalkRoomInfoSheet(
    visible: Boolean,
    session: AuthSession,
    state: TalkUiState,
    onDismiss: () -> Unit,
    onSearch: () -> Unit,
    onSearchQueryChange: (String) -> Unit,
    onAddParticipant: (String) -> Unit,
    onNotificationLevel: (Int) -> Unit,
    onLoadParticipants: () -> Unit,
) {
    if (!visible) return
    val room = state.selectedRoom ?: return
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = F7Colors.Surface) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text("О комнате", style = MaterialTheme.typography.titleMedium)
            Text(room.displayName, style = MaterialTheme.typography.titleSmall)
            Text("Тип: ${roomTypeLabel(room.type)}", color = F7Colors.TextSecondary)
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                F7SecondaryButton(text = "Все", onClick = { onNotificationLevel(1) })
                F7SecondaryButton(text = "@", onClick = { onNotificationLevel(2) })
                F7SecondaryButton(text = "Выкл.", onClick = { onNotificationLevel(3) })
            }
            F7TextButton(text = "Обновить участников", onClick = onLoadParticipants)
            if (state.participants.isNotEmpty()) {
                Text("Участники (${state.participants.size})", style = MaterialTheme.typography.labelMedium)
                state.participants.take(8).forEach { p ->
                    Text("• ${p.displayName}", style = MaterialTheme.typography.bodySmall)
                }
            }
            Spacer(Modifier.height(4.dp))
            Text("Поиск по сообщениям", style = MaterialTheme.typography.labelMedium)
            OutlinedTextField(
                value = state.messageSearchQuery,
                onValueChange = onSearchQueryChange,
                modifier = Modifier.fillMaxWidth(),
                placeholder = { Text("Минимум 2 символа") },
                singleLine = true,
            )
            F7PrimaryButton(
                text = if (state.messageSearchLoading) "Поиск…" else "Найти",
                onClick = onSearch,
            )
            if (state.messageSearchResults.isNotEmpty()) {
                LazyColumn(
                    modifier = Modifier.height(160.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp),
                ) {
                    items(state.messageSearchResults, key = { it.id }) { msg ->
                        Text(
                            "${msg.actorDisplayName}: ${formatMessageText(msg.text).take(80)}",
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                }
            }
            if (room.type == 2 && state.userSearchResults.isNotEmpty()) {
                Text("Добавить участника", style = MaterialTheme.typography.labelMedium)
                state.userSearchResults.take(5).forEach { user ->
                    F7TextButton(
                        text = "+ ${user.displayName}",
                        onClick = { onAddParticipant(user.userId) },
                    )
                }
            }
            Spacer(Modifier.height(24.dp))
        }
    }
}

@Composable
fun TalkReplyPreviewBar(
    message: TalkMessage?,
    onClear: () -> Unit,
    modifier: Modifier = Modifier,
) {
    if (message == null) return
    Row(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(F7Colors.Surface)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
            .padding(start = 12.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Box(
            modifier = Modifier
                .width(3.dp)
                .height(36.dp)
                .background(F7Colors.Primary, RoundedCornerShape(2.dp)),
        )
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(start = 8.dp),
        ) {
            Text(
                "Ответ ${message.actorDisplayName}",
                style = MaterialTheme.typography.labelSmall,
                color = F7Colors.Primary,
                fontWeight = FontWeight.Medium,
            )
            Text(
                formatMessageText(message.text).take(60),
                style = MaterialTheme.typography.bodySmall,
                color = F7Colors.TextSecondary,
            )
        }
        F7TextButton(text = "✕", onClick = onClear)
    }
}
